From 24991ef44765ba07cd6912d83b45ce38897efc76 Mon Sep 17 00:00:00 2001 From: KayzenRoot <114633702+KayzenRoot@users.noreply.github.com> Date: Fri, 20 Nov 2026 10:16:44 -0300 Subject: [PATCH 1/9] =?UTF-8?q?feat(wo-021):=20b=C3=ADblia=20audiovisual?= =?UTF-8?q?=20e=20presets=20(#38)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/CHECKPOINT_DELTA.md | 8 + docs/EVIDENCE_BUNDLE.md | 21 + docs/OPERATIONS.md | 8 + docs/V2_STYLE_WO021.md | 76 ++ docs/evidence/wo-021/tests.txt | 63 ++ e2e/owner-boundary.spec.ts | 9 +- e2e/responsive.ts | 25 +- e2e/style.spec.ts | 176 +++++ scripts/audit-policy.mjs | 26 +- scripts/backup-metadata.mjs | 4 + scripts/render-job.ts | 1 + scripts/restore-metadata.mjs | 4 + src/lib/components/WorkspaceNav.svelte | 6 + src/lib/domain/style-bible.test.ts | 208 +++++ src/lib/domain/style-bible.ts | 100 +++ src/lib/domain/style-config-hash.ts | 17 + src/lib/schemas/style-bible.ts | 150 ++++ src/lib/schemas/video-edit-plan.ts | 2 + src/lib/server/style-bible.ts | 623 +++++++++++++++ src/lib/server/video-edit-plans.test.ts | 82 ++ src/lib/server/video-edit-plans.ts | 30 +- src/routes/api/style/[presetId]/+server.ts | 31 + src/routes/app/style/+page.server.ts | 353 +++++++++ src/routes/app/style/+page.svelte | 744 ++++++++++++++++++ src/routes/app/style/StyleConfigFields.svelte | 524 ++++++++++++ src/routes/app/style/style-actions.test.ts | 223 ++++++ src/routes/app/timeline/+page.server.ts | 22 + src/routes/app/timeline/+page.svelte | 11 + .../20261120130000_v2_wo021_style_bible.sql | 232 ++++++ .../20261120131000_v2_wo021_style_quota.sql | 27 + supabase/tests/rls_and_integrity.sql | 128 ++- 31 files changed, 3924 insertions(+), 10 deletions(-) create mode 100644 docs/V2_STYLE_WO021.md create mode 100644 docs/evidence/wo-021/tests.txt create mode 100644 e2e/style.spec.ts create mode 100644 src/lib/domain/style-bible.test.ts create mode 100644 src/lib/domain/style-bible.ts create mode 100644 src/lib/domain/style-config-hash.ts create mode 100644 src/lib/schemas/style-bible.ts create mode 100644 src/lib/server/style-bible.ts create mode 100644 src/lib/server/video-edit-plans.test.ts create mode 100644 src/routes/api/style/[presetId]/+server.ts create mode 100644 src/routes/app/style/+page.server.ts create mode 100644 src/routes/app/style/+page.svelte create mode 100644 src/routes/app/style/StyleConfigFields.svelte create mode 100644 src/routes/app/style/style-actions.test.ts create mode 100644 supabase/migrations/20261120130000_v2_wo021_style_bible.sql create mode 100644 supabase/migrations/20261120131000_v2_wo021_style_quota.sql diff --git a/docs/CHECKPOINT_DELTA.md b/docs/CHECKPOINT_DELTA.md index baf3c4d8..1cb2f0bd 100644 --- a/docs/CHECKPOINT_DELTA.md +++ b/docs/CHECKPOINT_DELTA.md @@ -1,5 +1,13 @@ # Checkpoint Delta — CD06 +## DIF-V2-WO-021 — Bíblia audiovisual, presets e herança (2026-11-20) — PROPOSED / NOT PROMOTED + +- **Status:** implementação local concluída; PR Draft/CI/auditoria/merge pendentes. Sem deploy. +- **Base:** `main` `2fcfd89` (checkpoint WO-020 promovido); branch `feat/dif-v2-wo-021`. +- **Delivered:** presets versionados por série/temporada com revisão imutável e quota 200; overrides owner-only por episódio/cena; precedência por campo com origem; snapshot congelado no plano e hash; drift sinalizado no timeline; `/app/style`; export/import JSON estrito; auditoria de SFX; 4 tabelas RLS. +- **Limits:** render atual consome o snapshot e o color grade injetado; tipografia/legenda/SFX/capa/final permanecem referências congeladas para a evolução do renderizador. Sem backfill de séries existentes. +- **Gate:** pendente de CI/auditoria; WO-014 release segue bloqueada por OPS 015–021. + ## DIF-V2-WO-020 — Laboratório de retenção (2026-11-20) — PROMOTED - **Status:** **PROMOTED**; code/test head `02d9cae`; CI `44694433465` PASS (318+3 unit, PgTAP 229/229, E2E 18/18, Sonar PASS), docs-only `f22a4f7` CI `44696127263` PASS, policy 34/37; auditoria final **APPROVED WITH RESIDUALS**; squash-merged em `d9dd82b` (PR #67); issue #37 fechada. diff --git a/docs/EVIDENCE_BUNDLE.md b/docs/EVIDENCE_BUNDLE.md index 1772587c..5278f374 100644 --- a/docs/EVIDENCE_BUNDLE.md +++ b/docs/EVIDENCE_BUNDLE.md @@ -1,5 +1,26 @@ # DIF Studio — Evidence Bundle +## V2 WO-021 — Bíblia audiovisual, presets e herança (2026-11-20) — PROPOSED / NOT PROMOTED + +- **Work Order:** `DIF-V2-WO-021` · issue #38 · epic #17 +- **Base:** `main` `2fcfd89` (checkpoint WO-020 promovido); branch `feat/dif-v2-wo-021` +- **Status:** implementação local concluída; PR Draft, CI, auditoria independente, merge e promoção pendentes. Sem deploy. + +| Check | Result | Evidence | +| ---------- | ---------- | ---------------------------------------------------------------------------------------- | +| Model | PASS local | presets + revisões imutáveis por série/temporada; overrides owner-only por episódio/cena | +| Precedence | PASS local | DEFAULT document.documentElement.scrollWidth <= window.innerWidth, ); expect(fits, `${route} should not overflow at ${width}px`).toBe(true); - const slug = route === '/app' ? 'home' : route.replaceAll('/', '-').replace(/^-/, ''); + const slug = + route === '/app' + ? 'home' + : route + .replaceAll('/', '-') + .replace(/[^a-z0-9-]/gi, '-') + .replace(/^-+|-+$/g, ''); await page.screenshot({ path: path.join(screenshotDirectory, `app-${slug}-${width}.png`), fullPage: true, diff --git a/e2e/responsive.ts b/e2e/responsive.ts index a7c5c6a4..f652964f 100644 --- a/e2e/responsive.ts +++ b/e2e/responsive.ts @@ -13,10 +13,27 @@ export async function captureResponsivePages( await page.goto(input.url); await page.setViewportSize({ width, height: 900 }); await expect(page.getByRole('heading', { name: input.heading })).toBeVisible(); - const fits = await page.evaluate( - () => document.documentElement.scrollWidth <= window.innerWidth, - ); - expect(fits, `${input.prefix} should not overflow at ${width}px`).toBe(true); + const measure = await page.evaluate(() => ({ + fits: document.documentElement.scrollWidth <= window.innerWidth, + scrollWidth: document.documentElement.scrollWidth, + innerWidth: window.innerWidth, + offenders: Array.from(document.querySelectorAll('body *')) + .filter((element) => { + const rect = element.getBoundingClientRect(); + return rect.right > window.innerWidth + 1 || rect.width > window.innerWidth + 1; + }) + .slice(0, 8) + .map((element) => ({ + tag: element.tagName.toLowerCase(), + class: String(element.getAttribute('class') ?? '').slice(0, 80), + right: Math.round(element.getBoundingClientRect().right), + width: Math.round(element.getBoundingClientRect().width), + })), + })); + expect( + measure.fits, + `${input.prefix} should not overflow at ${width}px (scroll ${measure.scrollWidth} > ${measure.innerWidth}; ${JSON.stringify(measure.offenders)})`, + ).toBe(true); await page.screenshot({ path: path.join(screenshotDirectory, `${input.prefix}-${width}.png`), fullPage: true, diff --git a/e2e/style.spec.ts b/e2e/style.spec.ts new file mode 100644 index 00000000..58b9ed73 --- /dev/null +++ b/e2e/style.spec.ts @@ -0,0 +1,176 @@ +import { expect, test } from '@playwright/test'; +import { insertEpisodeHierarchy, loginAsOwner } from './fixtures.js'; +import { captureResponsivePages } from './responsive.js'; +import { insertRow, ownerAccessToken, ownerId, serviceKey, supabaseUrl } from './supabase.js'; + +test('two series keep distinct style bibles, overrides stay local and import is draft-only', async ({ + page, + request, +}) => { + test.setTimeout(300_000); + test.skip(!process.env.E2E_OWNER_EMAIL, 'requires a synthetic owner in local Supabase'); + test.skip(!supabaseUrl || !serviceKey || !ownerId, 'requires local service role and owner id'); + page.setDefaultTimeout(60_000); + page.setDefaultNavigationTimeout(120_000); + + const suffix = crypto.randomUUID().slice(0, 8); + const token = await ownerAccessToken(request); + const seriesA = await insertEpisodeHierarchy(request, { + token, + suffix: `${suffix}-a`, + seriesTitle: `Arquivo Alfa ${suffix}`, + premise: 'Série de arquivo analógico.', + seasonTitle: 'Temporada alfa', + plannedEpisodeCount: 10, + episodeNumber: 1, + episodeTitle: `Fita alfa ${suffix}`, + durationMs: 90_000, + }); + const seriesB = await insertEpisodeHierarchy(request, { + token, + suffix: `${suffix}-b`, + seriesTitle: `Sinal Beta ${suffix}`, + premise: 'Série de transmissão vhs.', + seasonTitle: 'Temporada beta', + plannedEpisodeCount: 10, + episodeNumber: 1, + episodeTitle: `Fita beta ${suffix}`, + durationMs: 90_000, + }); + await insertEpisodeHierarchy(request, { + token, + suffix: `${suffix}-long`, + seriesTitle: `Arquivo ${suffix} ${'registro-'.repeat(8)}`, + premise: 'Série de teste para títulos longos em selects estreitos.', + seasonTitle: `Temporada ${'extensa-'.repeat(6)}`, + plannedEpisodeCount: 10, + episodeNumber: 1, + episodeTitle: `Episódio ${'narrado-'.repeat(10)}`, + durationMs: 90_000, + }); + for (const episodeId of [seriesA.episodeId, seriesB.episodeId]) { + await insertRow(request, token, 'scenes', { + owner_id: ownerId, + episode_id: episodeId, + scene_index: 1, + start_ms: 0, + end_ms: 8_000, + }); + } + + await loginAsOwner(page); + const seriesUrl = (seriesId: string, episodeId: string) => + `/app/style?scopeType=SERIES&scopeId=${seriesId}&episodeId=${episodeId}`; + const waitHydrated = () => + expect(page.getByTestId('style-hydrated')).toHaveAttribute('data-hydrated', 'true'); + const openStyle = async (url: string) => { + await page.goto(url); + await waitHydrated(); + }; + + // Series A: mono, horror captions, VHS color and its own CTA. + await openStyle(seriesUrl(seriesA.seriesId, seriesA.episodeId)); + await expect(page.getByRole('heading', { name: 'Estilo da série' })).toBeVisible(); + const alphaForm = page.locator('form.style-form').first(); + await alphaForm.locator('input[name="name"]').fill(`Alfa ${suffix}`); + await alphaForm.locator('input[name="paletteAccent"]').fill('#ff0000'); + await alphaForm.locator('select[name="colorPresetId"]').selectOption('vhs_1987'); + await alphaForm.locator('select[name="fontFamily"]').selectOption('mono'); + await alphaForm.locator('select[name="captionTemplate"]').selectOption('horror'); + await alphaForm.locator('input[name="ctaPrompt"]').fill('Comente A'); + await expect(alphaForm.locator('select[name="fontFamily"]')).toHaveValue('mono'); + await expect(alphaForm.locator('select[name="captionTemplate"]')).toHaveValue('horror'); + await expect(page.locator('.live-preview')).toHaveClass(/font-mono/); + await alphaForm.getByRole('button', { name: 'Criar preset DRAFT' }).click(); + await expect(page.locator('.notice.success')).toContainText('Preset salvo como DRAFT'); + await page.getByRole('button', { name: 'Aprovar' }).first().click(); + await expect(page.locator('.notice.success')).toContainText('Preset aprovado'); + const exportHref = await page + .locator('.revision .actions a', { hasText: 'JSON' }) + .first() + .getAttribute('href'); + expect(exportHref).toMatch(/\/api\/style\//); + const exportUrl = new URL(exportHref!, page.url()).toString(); + + const alphaPreview = page.locator('.effective-preview'); + await expect(alphaPreview).toHaveClass(/font-mono/); + await expect(alphaPreview).toContainText('Comente A'); + expect(await alphaPreview.getAttribute('style')).toContain('--accent:#ff0000'); + + // Series B stays visually independent. + await openStyle(seriesUrl(seriesB.seriesId, seriesB.episodeId)); + await expect(page.getByRole('heading', { name: 'Estilo da série' })).toBeVisible(); + await page.waitForTimeout(1500); + const betaForm = page.locator('form.style-form').first(); + await betaForm.locator('input[name="name"]').fill(`Beta ${suffix}`); + await betaForm.locator('input[name="paletteAccent"]').fill('#00ff00'); + await betaForm.locator('select[name="fontFamily"]').selectOption('serif'); + await betaForm.locator('select[name="captionTemplate"]').selectOption('clean'); + await betaForm.locator('input[name="ctaPrompt"]').fill('Comente B'); + await betaForm.getByRole('button', { name: 'Criar preset DRAFT' }).click(); + await expect(page.locator('.notice.success')).toContainText('Preset salvo como DRAFT'); + await page.getByRole('button', { name: 'Aprovar' }).first().click(); + await expect(page.locator('.notice.success')).toContainText('Preset aprovado'); + const betaPreview = page.locator('.effective-preview'); + await expect(betaPreview).toHaveClass(/font-serif/); + await expect(betaPreview).toContainText('Comente B'); + expect(await betaPreview.getAttribute('style')).toContain('--accent:#00ff00'); + + // Episode override wins over the series without editing the preset. + await openStyle(seriesUrl(seriesA.seriesId, seriesA.episodeId)); + const episodePanel = page + .locator('section.panel') + .filter({ has: page.getByRole('heading', { name: 'Override do episódio' }) }); + await episodePanel.locator('select[name="captionTemplate"]').selectOption('clean'); + await episodePanel.getByRole('button', { name: 'Salvar override do episódio' }).click(); + await expect(page.locator('.notice.success')).toContainText('Override do episódio salvo'); + await waitHydrated(); + await expect(page.locator('.effective-preview')).toContainText('Comente A'); + await expect(page.locator('.effective-preview small')).toContainText('clean'); + + // Scene override adds only the scene layer to the frozen snapshot. + const scenePanel = page + .locator('section.panel') + .filter({ has: page.getByRole('heading', { name: 'Override da cena' }) }); + await scenePanel.locator('select[name="captionSafeZone"]').selectOption('feed'); + await scenePanel.getByRole('button', { name: 'Salvar override da cena' }).click(); + await expect(page.locator('.notice.success')).toContainText('Override da cena salvo'); + await waitHydrated(); + await page.locator('.scene-snapshot summary').click(); + await expect(page.locator('.scene-snapshot')).toContainText('feed'); + await expect(page.locator('.scene-snapshot')).toContainText('clean'); + + // Export carries validated config only; the series preset keeps horror/tiktok. + const exported = await page.request.get(exportUrl); + expect(exported.status()).toBe(200); + const payload = (await exported.json()) as { + format: string; + name: string; + config: { captionTemplate: string; captionSafeZone: string; ctaPrompt: string }; + }; + expect(payload.format).toBe('dif-studio-style-preset/v1'); + expect(payload.config.captionTemplate).toBe('horror'); + expect(payload.config.captionSafeZone).toBe('tiktok'); + expect(payload.config.ctaPrompt).toBe('Comente A'); + const raw = JSON.stringify(payload); + expect(raw).not.toContain('http'); + expect(raw).not.toContain('supabase'); + expect(raw).not.toContain('secret'); + const anonymous = await request.get(exportUrl); + expect([401, 403, 404]).toContain(anonymous.status()); + + // Importing A into B creates an unapproved draft and cannot change B's live style. + await openStyle(seriesUrl(seriesB.seriesId, seriesB.episodeId)); + await page.locator('textarea[name="json"]').fill(JSON.stringify(payload)); + await page.getByRole('button', { name: 'Importar como DRAFT' }).click(); + await expect(page.locator('.notice.success')).toContainText('Preset importado como DRAFT'); + await expect(page.locator('.revision')).toHaveCount(3); + await expect(page.locator('.effective-preview')).toContainText('Comente B'); + await expect(page.locator('.effective-preview')).toHaveClass(/font-serif/); + + await captureResponsivePages(page, { + url: seriesUrl(seriesA.seriesId, seriesA.episodeId), + heading: 'Estilo da série', + prefix: 'style', + }); +}); diff --git a/scripts/audit-policy.mjs b/scripts/audit-policy.mjs index 67fed274..b002a04a 100644 --- a/scripts/audit-policy.mjs +++ b/scripts/audit-policy.mjs @@ -86,6 +86,14 @@ const retentionLabMigration = await readFile( 'supabase/migrations/20261120110000_v2_wo020_retention_lab.sql', 'utf8', ); +const styleBibleMigration = await readFile( + 'supabase/migrations/20261120130000_v2_wo021_style_bible.sql', + 'utf8', +); +const styleBibleQuotaMigration = await readFile( + 'supabase/migrations/20261120131000_v2_wo021_style_quota.sql', + 'utf8', +); const retentionScript = await readFile('scripts/retention.mjs', 'utf8'); const restoreScript = await readFile('scripts/restore-metadata.mjs', 'utf8'); const hook = await readFile('src/hooks.server.ts', 'utf8'); @@ -126,9 +134,10 @@ const tables = [ ...coverMigration.matchAll(/^create table public\.(\w+)\s*\(/gm), ...endCardMigration.matchAll(/^create table public\.(\w+)\s*\(/gm), ...retentionLabMigration.matchAll(/^create table public\.(\w+)\s*\(/gm), + ...styleBibleMigration.matchAll(/^create table public\.(\w+)\s*\(/gm), ].map((match) => match[1]); const checks = [ - ['37 owner-scoped public tables', tables.length === 37], + ['41 owner-scoped public tables', tables.length === 41], [ 'every table has forced RLS', migration.includes('enable row level security') && @@ -432,6 +441,21 @@ const checks = [ retentionLabMigration.includes('snapshot_hash') && retentionLabMigration.includes('unique (owner_id, post_id, snapshot_hash)'), ], + [ + 'style bibles are owner-read, server-written and revision-immutable', + styleBibleMigration.includes('style_presets') && + styleBibleMigration.includes('style_preset_revisions') && + styleBibleMigration.includes('episode_style_overrides') && + styleBibleMigration.includes('scene_style_overrides') && + styleBibleMigration.includes('force row level security') && + styleBibleMigration.includes('grant select on table public.style_presets to authenticated') && + styleBibleMigration.includes('grant execute on function public.save_style_preset_revision') && + styleBibleMigration.includes('style_revision_is_immutable') && + styleBibleMigration.includes('style_revision_conflict') && + styleBibleMigration.includes('dif.style_prune') && + styleBibleQuotaMigration.includes('style_preset_revisions_quota') && + styleBibleQuotaMigration.includes('style_revision_quota'), + ], [ 'render quotas, health and ops scripts are server-only and dry-run first', hardeningMigration.includes('render_daily_job_quota') && diff --git a/scripts/backup-metadata.mjs b/scripts/backup-metadata.mjs index 4c9a6708..28b82ba9 100644 --- a/scripts/backup-metadata.mjs +++ b/scripts/backup-metadata.mjs @@ -97,6 +97,10 @@ const tableNames = [ 'retention_imports', 'analytics_snapshots', 'retention_experiments', + 'style_presets', + 'style_preset_revisions', + 'episode_style_overrides', + 'scene_style_overrides', ]; const counts = {}; for (const table of tableNames) { diff --git a/scripts/render-job.ts b/scripts/render-job.ts index 907cea4e..5aa9e3c6 100644 --- a/scripts/render-job.ts +++ b/scripts/render-job.ts @@ -475,6 +475,7 @@ async function main() { } : null, endCard: validated.endCard ?? null, + styleBible: validated.styleBible ?? null, bucket: localOutput ? 'local-test' : bucket, objectKey: localArtifactPath ?? objectKey, durationMs: output.durationMs, diff --git a/scripts/restore-metadata.mjs b/scripts/restore-metadata.mjs index 569ac12f..e0214a05 100644 --- a/scripts/restore-metadata.mjs +++ b/scripts/restore-metadata.mjs @@ -68,6 +68,10 @@ const allowedTables = new Set([ 'retention_imports', 'analytics_snapshots', 'retention_experiments', + 'style_presets', + 'style_preset_revisions', + 'episode_style_overrides', + 'scene_style_overrides', ]); for (const table of Object.keys(summary.counts)) { if (!allowedTables.has(table) || !/^[a-z][a-z0-9_]{0,63}$/.test(table)) diff --git a/src/lib/components/WorkspaceNav.svelte b/src/lib/components/WorkspaceNav.svelte index 159fd7c0..9fec9165 100644 --- a/src/lib/components/WorkspaceNav.svelte +++ b/src/lib/components/WorkspaceNav.svelte @@ -42,6 +42,12 @@ label: 'Retenção', glyph: 'archive', }, + { + path: '/app/style', + href: resolve('/app/style'), + label: 'Estilo', + glyph: 'book', + }, { path: '/app/library', href: resolve('/app/library'), diff --git a/src/lib/domain/style-bible.test.ts b/src/lib/domain/style-bible.test.ts new file mode 100644 index 00000000..bfdf2734 --- /dev/null +++ b/src/lib/domain/style-bible.test.ts @@ -0,0 +1,208 @@ +import { describe, expect, it } from 'vitest'; +import { + styleConfigSchema, + styleImportSchema, + styleOverrideSchema, + styleSnapshotSchema, +} from '#lib/schemas/style-bible.js'; +import { + DEFAULT_STYLE_CONFIG, + resolveStyle, + STYLE_FIELDS, + styleSnapshotDrift, + withdrawInvalidSfx, +} from './style-bible.js'; +import { styleConfigHash } from './style-config-hash.js'; + +function override(value: Record) { + return styleOverrideSchema.parse(value); +} + +const ALTERNATIVES: Record = { + paletteBackground: '#101112', + paletteForeground: '#f0e0d0', + paletteAccent: '#ff5500', + paletteMuted: '#777777', + colorPresetId: 'vhs_1987', + colorStrength: 0.33, + fontFamily: 'mono', + captionTemplate: 'horror', + captionSafeZone: 'feed', + motion: 'kinetic', + reducedMotion: true, + vhsIntensity: 3, + sfxCategory: 'pulse', + sfxAssetIds: ['a1a1a1a1-a1a1-41a1-81a1-a1a1a1a1a1a1'], + voiceStyle: 'whisper', + openingHookKind: 'sound_entry', + coverTemplateId: 'cctv', + endCardTemplateId: 'signal', + ctaPrompt: 'Responda com uma palavra', +}; + +describe('style bible resolution', () => { + it('resolves defaults, series, season, episode and scene precedence per field', () => { + const resolved = resolveStyle([ + { source: 'SERIES', config: override({ paletteAccent: '#ff0000', fontFamily: 'serif' }) }, + { source: 'SEASON', config: override({ paletteAccent: '#00ff00', vhsIntensity: 0 }) }, + { source: 'EPISODE', config: override({ captionTemplate: 'horror' }) }, + { source: 'SCENE', config: override({ motion: 'kinetic', reducedMotion: true }) }, + ]); + expect(resolved.config.paletteAccent).toBe('#00ff00'); + expect(resolved.config.fontFamily).toBe('serif'); + expect(resolved.config.vhsIntensity).toBe(0); + expect(resolved.config.captionTemplate).toBe('horror'); + expect(resolved.config.motion).toBe('kinetic'); + expect(resolved.config.reducedMotion).toBe(true); + expect(resolved.sources.paletteAccent).toBe('SEASON'); + expect(resolved.sources.fontFamily).toBe('SERIES'); + expect(resolved.sources.vhsIntensity).toBe('SEASON'); + expect(resolved.sources.captionTemplate).toBe('EPISODE'); + expect(resolved.sources.motion).toBe('SCENE'); + expect(resolved.sources.paletteBackground).toBe('DEFAULT'); + }); + + it('lets a scene override win every field without mutating the series layer', () => { + for (const field of STYLE_FIELDS) { + const series = override({ [field]: ALTERNATIVES[field] }); + const seriesBefore = structuredClone(series); + const resolved = resolveStyle([ + { source: 'SERIES', config: series }, + { source: 'EPISODE', config: override({ [field]: DEFAULT_STYLE_CONFIG[field] }) }, + { source: 'SCENE', config: override({ [field]: ALTERNATIVES[field] }) }, + ]); + expect(resolved.config[field], field).toEqual(ALTERNATIVES[field]); + expect(resolved.sources[field], field).toBe('SCENE'); + expect(series, field).toEqual(seriesBefore); + } + }); + + it('keeps a scene caption override scoped without changing the series preset', () => { + const series = override({ paletteAccent: '#123456', captionTemplate: 'clean' }); + const resolved = resolveStyle([ + { source: 'SERIES', config: series }, + { source: 'SCENE', config: override({ captionTemplate: 'horror' }) }, + ]); + expect(resolved.config.captionTemplate).toBe('horror'); + expect(resolved.sources.captionTemplate).toBe('SCENE'); + expect(resolved.config.paletteAccent).toBe('#123456'); + expect(resolved.sources.paletteAccent).toBe('SERIES'); + expect(series.captionTemplate).toBe('clean'); + }); + + it('treats false and zero as explicit overrides', () => { + const resolved = resolveStyle([ + { source: 'EPISODE', config: override({ reducedMotion: false, vhsIntensity: 0 }) }, + ]); + expect(resolved.config.reducedMotion).toBe(false); + expect(resolved.config.vhsIntensity).toBe(0); + expect(resolved.sources.reducedMotion).toBe('EPISODE'); + }); + + it('hashes deterministically and changes with any visual field', () => { + const base = DEFAULT_STYLE_CONFIG; + expect(styleConfigHash(base)).toBe(styleConfigHash({ ...base })); + expect(styleConfigHash(base)).not.toBe( + styleConfigHash(styleConfigSchema.parse({ ...base, paletteAccent: '#abcdef' })), + ); + expect(styleConfigHash(base)).not.toBe( + styleConfigHash(styleConfigSchema.parse({ ...base, captionTemplate: 'horror' })), + ); + expect(STYLE_FIELDS.every((field) => field in base)).toBe(true); + }); + + it('roundtrips the versioned import envelope and rejects unknown fields or versions', () => { + const payload = { + format: 'dif-studio-style-preset/v1', + name: 'Noir reutilizável', + scopeType: 'SERIES', + scopeId: 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa', + config: DEFAULT_STYLE_CONFIG, + }; + expect(styleImportSchema.parse(payload)).toMatchObject({ name: 'Noir reutilizável' }); + expect(styleImportSchema.safeParse({ ...payload, format: 'v2' }).success).toBe(false); + expect( + styleImportSchema.safeParse({ + ...payload, + config: { ...DEFAULT_STYLE_CONFIG, shellCommand: 'rm -rf /' }, + }).success, + ).toBe(false); + expect(styleOverrideSchema.parse({})).toEqual({}); + }); + + it('withdraws only missing or unlicensed SFX and keeps the rest', () => { + const config = styleConfigSchema.parse({ + ...DEFAULT_STYLE_CONFIG, + sfxAssetIds: ['a1a1a1a1-a1a1-41a1-81a1-a1a1a1a1a1a1', 'b2b2b2b2-b2b2-42b2-82b2-b2b2b2b2b2b2'], + }); + const filtered = withdrawInvalidSfx(config, new Set(['b2b2b2b2-b2b2-42b2-82b2-b2b2b2b2b2b2'])); + expect(filtered.sfxAssetIds).toEqual(['b2b2b2b2-b2b2-42b2-82b2-b2b2b2b2b2b2']); + expect(withdrawInvalidSfx(config, new Set(config.sfxAssetIds))).toBe(config); + }); + + it('detects preset, config and scene drift without mutating frozen snapshots', () => { + const base = styleSnapshotSchema.parse({ + presetId: null, + presetRevision: 4, + presetHash: 'a'.repeat(64), + scopeType: 'SERIES', + scopeId: null, + config: DEFAULT_STYLE_CONFIG, + sources: {}, + scenes: [], + warnings: [], + capturedAt: '2026-11-20T12:00:00Z', + }); + expect(styleSnapshotDrift(base, base).stale).toBe(false); + expect(styleSnapshotDrift(base, { ...base, presetRevision: 5 }).stale).toBe(true); + expect( + styleSnapshotDrift(base, { + ...base, + config: { ...base.config, paletteAccent: '#ff0000' }, + }).stale, + ).toBe(true); + expect( + styleSnapshotDrift(base, { + ...base, + scenes: [ + { + sceneId: 'cccccccc-cccc-4ccc-8ccc-cccccccccccc', + sceneIndex: 1, + config: { ...base.config, captionTemplate: 'horror' }, + sources: { captionTemplate: 'SCENE' }, + }, + ], + }).stale, + ).toBe(true); + expect(base.presetRevision).toBe(4); + }); + + it('accepts frozen scene snapshots with per-field sources', () => { + const snapshot = styleSnapshotSchema.parse({ + presetId: null, + presetRevision: null, + presetHash: null, + scopeType: null, + scopeId: null, + config: DEFAULT_STYLE_CONFIG, + sources: { paletteAccent: 'DEFAULT' }, + scenes: [ + { + sceneId: 'cccccccc-cccc-4ccc-8ccc-cccccccccccc', + sceneIndex: 1, + config: { ...DEFAULT_STYLE_CONFIG, captionTemplate: 'horror' }, + sources: { captionTemplate: 'SCENE' }, + }, + ], + warnings: ['STYLE_PRESET_MISSING'], + capturedAt: '2026-11-20T12:00:00Z', + }); + expect(snapshot.scenes?.[0]?.sources.captionTemplate).toBe('SCENE'); + expect( + styleSnapshotSchema.safeParse({ + ...snapshot, + capturedAt: 'not-a-date', + }).success, + ).toBe(false); + }); +}); diff --git a/src/lib/domain/style-bible.ts b/src/lib/domain/style-bible.ts new file mode 100644 index 00000000..9818b981 --- /dev/null +++ b/src/lib/domain/style-bible.ts @@ -0,0 +1,100 @@ +import { + STYLE_BIBLE_VERSION, + styleConfigSchema, + type StyleConfig, + type StyleOverride, + type StyleSnapshot, +} from '#lib/schemas/style-bible.js'; + +export class StyleBibleError extends Error { + constructor( + readonly code: string, + message: string, + ) { + super(message); + this.name = 'StyleBibleError'; + } +} + +export const DEFAULT_STYLE_CONFIG: StyleConfig = styleConfigSchema.parse({ + schemaVersion: STYLE_BIBLE_VERSION, +}); + +export const STYLE_FIELDS = Object.keys(DEFAULT_STYLE_CONFIG).filter( + (field): field is keyof StyleConfig => field !== 'schemaVersion', +); + +export interface StyleLayer { + source: 'SERIES' | 'SEASON' | 'EPISODE' | 'SCENE'; + config: StyleOverride | null; +} + +export interface ResolvedStyle { + config: StyleConfig; + sources: Record; +} + +export function resolveStyle(layers: StyleLayer[]): ResolvedStyle { + const config: Record = { ...DEFAULT_STYLE_CONFIG }; + const sources: Record = {}; + for (const field of STYLE_FIELDS) sources[field] = 'DEFAULT'; + for (const layer of layers) { + if (!layer.config) continue; + for (const field of STYLE_FIELDS) { + const value = layer.config[field]; + if (value !== undefined) { + config[field] = value; + sources[field] = layer.source; + } + } + } + return { config: styleConfigSchema.parse(config), sources }; +} + +export function withdrawInvalidSfx( + config: StyleConfig, + validIds: ReadonlySet, +): StyleConfig { + const kept = config.sfxAssetIds.filter((id) => validIds.has(id)); + if (kept.length === config.sfxAssetIds.length) return config; + return { ...config, sfxAssetIds: kept }; +} + +export interface StyleSnapshotDrift { + stale: boolean; + capturedRevision: number | null; + currentRevision: number | null; + capturedHash: string | null; + currentHash: string | null; + configChanged: boolean; + scenesChanged: boolean; +} + +export function styleSnapshotDrift( + captured: StyleSnapshot, + current: StyleSnapshot, +): StyleSnapshotDrift { + const configChanged = JSON.stringify(captured.config) !== JSON.stringify(current.config); + const scenesChanged = + JSON.stringify(captured.scenes ?? []) !== JSON.stringify(current.scenes ?? []); + return { + stale: + captured.presetRevision !== current.presetRevision || + captured.presetHash !== current.presetHash || + configChanged || + scenesChanged, + capturedRevision: captured.presetRevision, + currentRevision: current.presetRevision, + capturedHash: captured.presetHash, + currentHash: current.presetHash, + configChanged, + scenesChanged, + }; +} + +export function styleFontStack(fontFamily: StyleConfig['fontFamily']): string { + if (fontFamily === 'serif') return 'Georgia, "Times New Roman", serif'; + if (fontFamily === 'mono') return '"Courier New", Consolas, monospace'; + if (fontFamily === 'display') return 'Impact, "Arial Black", sans-serif'; + return 'Arial, "DejaVu Sans", sans-serif'; +} diff --git a/src/lib/domain/style-config-hash.ts b/src/lib/domain/style-config-hash.ts new file mode 100644 index 00000000..60395f47 --- /dev/null +++ b/src/lib/domain/style-config-hash.ts @@ -0,0 +1,17 @@ +import { createHash } from 'node:crypto'; +import { STYLE_BIBLE_VERSION, type StyleConfig } from '#lib/schemas/style-bible.js'; +import { canonicalJson } from './canonical-json.js'; + +export const STYLE_HASH_VERSION = 1; + +export function styleConfigHash(config: StyleConfig): string { + return createHash('sha256') + .update( + canonicalJson({ + hashVersion: STYLE_HASH_VERSION, + bibleVersion: STYLE_BIBLE_VERSION, + config, + }), + ) + .digest('hex'); +} diff --git a/src/lib/schemas/style-bible.ts b/src/lib/schemas/style-bible.ts new file mode 100644 index 00000000..79ed1afc --- /dev/null +++ b/src/lib/schemas/style-bible.ts @@ -0,0 +1,150 @@ +import { z } from 'zod'; +import { COLOR_PRESET_IDS } from './color-grade.js'; +import { COVER_TEMPLATE_IDS } from './cover.js'; +import { CHOICE_END_CARD_TEMPLATE_IDS } from './choice-end-card.js'; + +const uuid = z.string().uuid(); +const hex = z.string().regex(/^#[0-9a-f]{6}$/i, 'Cor deve ser hexadecimal #rrggbb.'); + +export const STYLE_SCOPE_TYPES = ['SERIES', 'SEASON'] as const; +export const STYLE_FONT_FAMILIES = ['serif', 'sans', 'mono', 'display'] as const; +export const STYLE_CAPTION_TEMPLATES = ['none', 'clean', 'horror'] as const; +export const STYLE_CAPTION_SAFE_ZONES = ['tiktok', 'stories', 'feed'] as const; +export const STYLE_MOTION = ['restrained', 'standard', 'kinetic'] as const; +export const STYLE_SFX_CATEGORIES = ['none', 'archive', 'signal', 'pulse', 'ambience'] as const; +export const STYLE_VOICE_STYLES = ['neutral', 'documentary', 'whisper', 'urgent', 'none'] as const; +export const STYLE_OPENING_HOOKS = ['none', 'cold_open', 'intriguing_line', 'sound_entry'] as const; + +export type StyleScopeType = (typeof STYLE_SCOPE_TYPES)[number]; +export type StyleFontFamily = (typeof STYLE_FONT_FAMILIES)[number]; +export type StyleCaptionTemplate = (typeof STYLE_CAPTION_TEMPLATES)[number]; +export type StyleCaptionSafeZone = (typeof STYLE_CAPTION_SAFE_ZONES)[number]; +export type StyleMotion = (typeof STYLE_MOTION)[number]; +export type StyleSfxCategory = (typeof STYLE_SFX_CATEGORIES)[number]; +export type StyleVoiceStyle = (typeof STYLE_VOICE_STYLES)[number]; +export type StyleOpeningHook = (typeof STYLE_OPENING_HOOKS)[number]; + +export const STYLE_BIBLE_VERSION = 1; + +const styleFields = { + paletteBackground: hex, + paletteForeground: hex, + paletteAccent: hex, + paletteMuted: hex, + colorPresetId: z.enum(COLOR_PRESET_IDS), + colorStrength: z.number().min(0).max(1), + fontFamily: z.enum(STYLE_FONT_FAMILIES), + captionTemplate: z.enum(STYLE_CAPTION_TEMPLATES), + captionSafeZone: z.enum(STYLE_CAPTION_SAFE_ZONES), + motion: z.enum(STYLE_MOTION), + reducedMotion: z.boolean(), + vhsIntensity: z.union([z.literal(0), z.literal(1), z.literal(2), z.literal(3)]), + sfxCategory: z.enum(STYLE_SFX_CATEGORIES), + sfxAssetIds: z.array(uuid).max(8), + voiceStyle: z.enum(STYLE_VOICE_STYLES), + openingHookKind: z.enum(STYLE_OPENING_HOOKS), + coverTemplateId: z.enum(COVER_TEMPLATE_IDS), + endCardTemplateId: z.enum(CHOICE_END_CARD_TEMPLATE_IDS), + ctaPrompt: z.string().trim().min(1).max(80), +}; + +export const styleConfigSchema = z + .object({ + schemaVersion: z.literal(STYLE_BIBLE_VERSION), + paletteBackground: styleFields.paletteBackground.default('#08090b'), + paletteForeground: styleFields.paletteForeground.default('#e8e2d6'), + paletteAccent: styleFields.paletteAccent.default('#b6ff9a'), + paletteMuted: styleFields.paletteMuted.default('#8a8a8a'), + colorPresetId: styleFields.colorPresetId.default('neutral'), + colorStrength: styleFields.colorStrength.default(1), + fontFamily: styleFields.fontFamily.default('sans'), + captionTemplate: styleFields.captionTemplate.default('clean'), + captionSafeZone: styleFields.captionSafeZone.default('tiktok'), + motion: styleFields.motion.default('restrained'), + reducedMotion: styleFields.reducedMotion.default(false), + vhsIntensity: styleFields.vhsIntensity.default(1), + sfxCategory: styleFields.sfxCategory.default('none'), + sfxAssetIds: styleFields.sfxAssetIds.default([]), + voiceStyle: styleFields.voiceStyle.default('neutral'), + openingHookKind: styleFields.openingHookKind.default('none'), + coverTemplateId: styleFields.coverTemplateId.default('noir'), + endCardTemplateId: styleFields.endCardTemplateId.default('doors'), + ctaPrompt: styleFields.ctaPrompt.default('Comente A ou B'), + }) + .strict(); + +export type StyleConfig = z.infer; + +export const styleOverrideSchema = z + .object({ + schemaVersion: z.literal(STYLE_BIBLE_VERSION).optional(), + paletteBackground: styleFields.paletteBackground.optional(), + paletteForeground: styleFields.paletteForeground.optional(), + paletteAccent: styleFields.paletteAccent.optional(), + paletteMuted: styleFields.paletteMuted.optional(), + colorPresetId: styleFields.colorPresetId.optional(), + colorStrength: styleFields.colorStrength.optional(), + fontFamily: styleFields.fontFamily.optional(), + captionTemplate: styleFields.captionTemplate.optional(), + captionSafeZone: styleFields.captionSafeZone.optional(), + motion: styleFields.motion.optional(), + reducedMotion: styleFields.reducedMotion.optional(), + vhsIntensity: styleFields.vhsIntensity.optional(), + sfxCategory: styleFields.sfxCategory.optional(), + sfxAssetIds: styleFields.sfxAssetIds.optional(), + voiceStyle: styleFields.voiceStyle.optional(), + openingHookKind: styleFields.openingHookKind.optional(), + coverTemplateId: styleFields.coverTemplateId.optional(), + endCardTemplateId: styleFields.endCardTemplateId.optional(), + ctaPrompt: styleFields.ctaPrompt.optional(), + }) + .strict(); + +export type StyleOverride = z.infer; + +export const styleSourcesSchema = z.record( + z.string(), + z.enum(['DEFAULT', 'SERIES', 'SEASON', 'EPISODE', 'SCENE']), +); + +export const styleSceneSnapshotSchema = z.object({ + sceneId: uuid, + sceneIndex: z.number().int().min(1).max(500), + config: styleConfigSchema, + sources: styleSourcesSchema, +}); + +export const styleSnapshotSchema = z.object({ + presetId: uuid.nullable(), + presetRevision: z.number().int().min(1).nullable(), + presetHash: z + .string() + .regex(/^[0-9a-f]{64}$/) + .nullable(), + scopeType: z.enum(STYLE_SCOPE_TYPES).nullable(), + scopeId: uuid.nullable(), + config: styleConfigSchema, + sources: styleSourcesSchema, + scenes: z.array(styleSceneSnapshotSchema).max(60).optional(), + warnings: z.array(z.string().max(200)).max(20).default([]), + capturedAt: z.string().datetime({ offset: true }), +}); + +export type StyleSnapshot = z.infer; + +export const stylePresetSaveSchema = z.object({ + scopeType: z.enum(STYLE_SCOPE_TYPES), + scopeId: uuid, + name: z.string().trim().min(1).max(80), + expectedRevision: z.number().int().min(0).max(10_000), + config: styleConfigSchema, + status: z.enum(['DRAFT', 'APPROVED']).default('DRAFT'), +}); + +export const styleImportSchema = z.object({ + format: z.literal('dif-studio-style-preset/v1'), + name: z.string().trim().min(1).max(80), + scopeType: z.enum(STYLE_SCOPE_TYPES), + scopeId: uuid, + config: styleConfigSchema, +}); diff --git a/src/lib/schemas/video-edit-plan.ts b/src/lib/schemas/video-edit-plan.ts index 4078d453..eaa955c5 100644 --- a/src/lib/schemas/video-edit-plan.ts +++ b/src/lib/schemas/video-edit-plan.ts @@ -4,6 +4,7 @@ import { editDirectorPlanSchema } from './edit-director.js'; import { editPlanPreviewSchema } from './platform-preview.js'; import { colorGradeSchema } from './color-grade.js'; import { editPlanEndCardSchema } from './choice-end-card.js'; +import { styleSnapshotSchema } from './style-bible.js'; const uuid = z.string().uuid(); const millisecond = z.number().int().min(0).max(150_000); @@ -67,6 +68,7 @@ export const videoEditPlanSchema = z.object({ .default({ template: 'clean' }), cta: editPlanCtaSchema.nullable().default(null), endCard: editPlanEndCardSchema.nullable().optional(), + styleBible: styleSnapshotSchema.nullable().optional(), audio: editPlanAudioSchema.optional(), director: editDirectorPlanSchema.optional(), preview: editPlanPreviewSchema.optional(), diff --git a/src/lib/server/style-bible.ts b/src/lib/server/style-bible.ts new file mode 100644 index 00000000..c7af046d --- /dev/null +++ b/src/lib/server/style-bible.ts @@ -0,0 +1,623 @@ +import type { SupabaseClient, User } from '@supabase/supabase-js'; +import { + styleConfigSchema, + styleImportSchema, + styleOverrideSchema, + stylePresetSaveSchema, + type StyleConfig, + type StyleOverride, + type StyleScopeType, + type StyleSnapshot, +} from '#lib/schemas/style-bible.js'; +import { resolveStyle, withdrawInvalidSfx, type StyleLayer } from '#lib/domain/style-bible.js'; +import { styleConfigHash, STYLE_HASH_VERSION } from '#lib/domain/style-config-hash.js'; +import { firstRelation } from './relations.js'; + +export class StyleServiceError extends Error { + constructor( + readonly status: number, + readonly code: string, + message: string, + ) { + super(message); + this.name = 'StyleServiceError'; + } +} + +interface PresetRow { + id: string; + owner_id: string; + scope_type: string; + scope_id: string; + name: string; + created_at: string; + updated_at: string; +} + +interface RevisionRow { + id: string; + preset_id: string; + revision_number: number; + config: unknown; + config_hash: string; + hash_version: number; + status: string; + created_at: string; +} + +export interface StyleRevision { + id: string; + revision: number; + status: 'DRAFT' | 'APPROVED'; + config: StyleConfig; + configHash: string; + createdAt: string; +} + +export interface StylePreset { + id: string; + scopeType: StyleScopeType; + scopeId: string; + name: string; + revisions: StyleRevision[]; + latestRevision: number; + approved: StyleRevision | null; +} + +export interface StylePageContext { + presets: StylePreset[]; + series: Array<{ id: string; title: string }>; + seasons: Array<{ id: string; title: string; seriesId: string; seriesTitle: string }>; + episodes: Array<{ + id: string; + title: string; + number: number; + seriesTitle: string; + seriesId: string | null; + seasonId: string | null; + }>; + episodeOverrides: Array<{ episodeId: string; config: StyleOverride }>; + sceneOverrides: Array<{ sceneId: string; episodeId: string; config: StyleOverride }>; +} + +function mapRpcError(error: { code?: string; message?: string }): StyleServiceError { + if (error.code === '40001') + return new StyleServiceError( + 409, + 'STYLE_REVISION_CONFLICT', + 'O estilo foi alterado em outra aba. Recarregue antes de salvar.', + ); + if (error.code === 'P0002') + return new StyleServiceError(404, 'STYLE_SCOPE_NOT_FOUND', 'Série/temporada não encontrada.'); + if (error.code === '55000') + return new StyleServiceError( + 409, + 'STYLE_IMMUTABLE', + 'O histórico de estilo é imutável; crie uma nova revisão.', + ); + if (error.code === '23514') { + if (error.message?.includes('style_revision_quota')) + return new StyleServiceError( + 409, + 'STYLE_REVISION_QUOTA', + 'Este preset atingiu 200 revisões. Duplique-o para continuar.', + ); + return new StyleServiceError(400, 'STYLE_INVALID', 'Configuração de estilo inválida.'); + } + if (error.code === '23505') + return new StyleServiceError( + 409, + 'STYLE_REVISION_CONFLICT', + 'O preset foi criado em outra aba. Recarregue antes de salvar.', + ); + if (error.code === '42501') + return new StyleServiceError(403, 'STYLE_FORBIDDEN', 'Acesso não autorizado.'); + return new StyleServiceError(503, 'STYLE_SAVE_FAILED', 'Não foi possível salvar o estilo.'); +} + +async function validateSfxAssets( + db: SupabaseClient, + owner: User, + config: StyleConfig, +): Promise { + if (!config.sfxAssetIds.length) return; + const { data, error } = await db + .from('audio_assets') + .select('id,license_status,commercial_allowed,social_allowed') + .eq('owner_id', owner.id) + .in('id', config.sfxAssetIds); + if (error) + throw new StyleServiceError(503, 'STYLE_ASSET_LOAD_FAILED', 'Não foi possível validar os SFX.'); + const rows = data ?? []; + if (rows.length !== new Set(config.sfxAssetIds).size) + throw new StyleServiceError( + 409, + 'STYLE_ASSET_MISSING', + 'Um ou mais SFX do preset não existem mais. Corrija o preset.', + ); + const unlicensed = rows.some( + (row) => row.license_status !== 'VERIFIED' || !row.commercial_allowed || !row.social_allowed, + ); + if (unlicensed) + throw new StyleServiceError( + 409, + 'STYLE_LICENSE_BLOCKED', + 'Um ou mais SFX não têm licença verificada para uso comercial/social.', + ); +} + +function parseRevision(row: RevisionRow): StyleRevision { + const parsed = styleConfigSchema.safeParse(row.config); + if (!parsed.success) + throw new StyleServiceError(500, 'STYLE_STORED_INVALID', 'Estilo armazenado inválido.'); + if (styleConfigHash(parsed.data) !== row.config_hash) + throw new StyleServiceError(500, 'STYLE_HASH_MISMATCH', 'O hash do estilo não confere.'); + return { + id: row.id, + revision: Number(row.revision_number), + status: row.status === 'APPROVED' ? 'APPROVED' : 'DRAFT', + config: parsed.data, + configHash: row.config_hash, + createdAt: row.created_at, + }; +} + +async function loadPresetForScope( + db: SupabaseClient, + owner: User, + scopeType: StyleScopeType, + scopeId: string, +): Promise { + const { data: preset, error } = await db + .from('style_presets') + .select('*') + .eq('owner_id', owner.id) + .eq('scope_type', scopeType) + .eq('scope_id', scopeId) + .maybeSingle(); + if (error) + throw new StyleServiceError(503, 'STYLE_LOAD_FAILED', 'Não foi possível carregar o estilo.'); + if (!preset) return null; + const { data: revisions, error: revisionsError } = await db + .from('style_preset_revisions') + .select('*') + .eq('owner_id', owner.id) + .eq('preset_id', preset.id) + .order('revision_number', { ascending: false }) + .limit(200); + if (revisionsError) + throw new StyleServiceError(503, 'STYLE_LOAD_FAILED', 'Não foi possível carregar o estilo.'); + const mapped = ((revisions ?? []) as RevisionRow[]).map(parseRevision); + return { + id: preset.id as string, + scopeType: preset.scope_type as StyleScopeType, + scopeId: preset.scope_id as string, + name: preset.name as string, + revisions: mapped, + latestRevision: mapped[0]?.revision ?? 0, + approved: mapped.find((revision) => revision.status === 'APPROVED') ?? null, + }; +} + +export async function saveStylePreset(input: { + db: SupabaseClient; + adminDb: SupabaseClient | null; + owner: User; + values: unknown; +}): Promise<{ revision: number; presetId: string | null }> { + const parsed = stylePresetSaveSchema.safeParse(input.values); + if (!parsed.success) + throw new StyleServiceError(400, 'STYLE_INVALID', 'Configuração de estilo inválida.'); + await validateSfxAssets(input.db, input.owner, parsed.data.config); + if (!input.adminDb) + throw new StyleServiceError( + 503, + 'STYLE_WRITE_UNAVAILABLE', + 'O writer de estilo não está configurado.', + ); + const { data, error } = await input.adminDb.rpc('save_style_preset_revision', { + p_owner_id: input.owner.id, + p_scope_type: parsed.data.scopeType, + p_scope_id: parsed.data.scopeId, + p_name: parsed.data.name, + p_expected_revision: parsed.data.expectedRevision, + p_config: parsed.data.config, + p_config_hash: styleConfigHash(parsed.data.config), + p_status: parsed.data.status, + }); + if (error) throw mapRpcError(error); + if (typeof data !== 'number') + throw new StyleServiceError(503, 'STYLE_SAVE_FAILED', 'O servidor não retornou a revisão.'); + return { revision: data, presetId: null }; +} + +export async function saveEpisodeStyleOverride(input: { + db: SupabaseClient; + adminDb: SupabaseClient | null; + owner: User; + episodeId: string; + config: unknown; +}): Promise { + const parsed = styleOverrideSchema.safeParse(input.config); + if (!parsed.success) + throw new StyleServiceError(400, 'STYLE_OVERRIDE_INVALID', 'Override de episódio inválido.'); + if (parsed.data.sfxAssetIds?.length) + await validateSfxAssets( + input.db, + input.owner, + styleConfigSchema.parse({ schemaVersion: 1, ...parsed.data }), + ); + if (!input.adminDb) + throw new StyleServiceError( + 503, + 'STYLE_WRITE_UNAVAILABLE', + 'O writer de estilo não está configurado.', + ); + const { error } = await input.adminDb.rpc('save_episode_style_override', { + p_owner_id: input.owner.id, + p_episode_id: input.episodeId, + p_config: parsed.data, + }); + if (error) throw mapRpcError(error); +} + +export async function saveSceneStyleOverride(input: { + db: SupabaseClient; + adminDb: SupabaseClient | null; + owner: User; + sceneId: string; + config: unknown; +}): Promise { + const parsed = styleOverrideSchema.safeParse(input.config); + if (!parsed.success) + throw new StyleServiceError(400, 'STYLE_OVERRIDE_INVALID', 'Override de cena inválido.'); + if (parsed.data.sfxAssetIds?.length) + await validateSfxAssets( + input.db, + input.owner, + styleConfigSchema.parse({ schemaVersion: 1, ...parsed.data }), + ); + if (!input.adminDb) + throw new StyleServiceError( + 503, + 'STYLE_WRITE_UNAVAILABLE', + 'O writer de estilo não está configurado.', + ); + const { error } = await input.adminDb.rpc('save_scene_style_override', { + p_owner_id: input.owner.id, + p_scene_id: input.sceneId, + p_config: parsed.data, + }); + if (error) throw mapRpcError(error); +} + +export async function loadStylePageContext( + db: SupabaseClient, + owner: User, +): Promise { + const [ + seriesResult, + seasonsResult, + episodesResult, + presetsResult, + episodesOverrides, + scenesOverrides, + ] = await Promise.all([ + db.from('series').select('id,title').eq('owner_id', owner.id).order('title').limit(200), + db + .from('seasons') + .select('id,title,series_id,series(title)') + .eq('owner_id', owner.id) + .order('season_number') + .limit(500), + db + .from('episodes') + .select('id,title,episode_number,seasons(id,series_id,title,series(title))') + .eq('owner_id', owner.id) + .order('episode_number') + .limit(1_000), + db.from('style_presets').select('*').eq('owner_id', owner.id).limit(500), + db + .from('episode_style_overrides') + .select('episode_id,config') + .eq('owner_id', owner.id) + .limit(1_000), + db + .from('scene_style_overrides') + .select('scene_id,config,scenes(episode_id)') + .eq('owner_id', owner.id) + .limit(1_000), + ]); + if ( + seriesResult.error || + seasonsResult.error || + episodesResult.error || + presetsResult.error || + episodesOverrides.error || + scenesOverrides.error + ) + throw new StyleServiceError(503, 'STYLE_LOAD_FAILED', 'Não foi possível carregar a bíblia.'); + const presets: StylePreset[] = []; + for (const preset of (presetsResult.data ?? []) as PresetRow[]) { + const loaded = await loadPresetForScope( + db, + owner, + preset.scope_type as StyleScopeType, + preset.scope_id, + ); + if (loaded) presets.push(loaded); + } + const series = (seriesResult.data ?? []).map((row) => ({ + id: row.id as string, + title: row.title as string, + })); + const seasons = ((seasonsResult.data ?? []) as Array>).map((row) => { + const related = firstRelation(row.series) as { title?: string } | null; + return { + id: row.id as string, + title: row.title as string, + seriesId: row.series_id as string, + seriesTitle: related?.title ?? 'Série', + }; + }); + const episodes = ((episodesResult.data ?? []) as Array>).map((row) => { + const season = firstRelation(row.seasons) as { + id?: string; + title?: string; + series_id?: string; + series?: unknown; + } | null; + const related = season ? (firstRelation(season.series) as { title?: string } | null) : null; + return { + id: row.id as string, + title: row.title as string, + number: Number(row.episode_number), + seriesTitle: related?.title ?? 'Série', + seriesId: season?.series_id ?? null, + seasonId: season?.id ?? null, + }; + }); + const episodeOverrides = ((episodesOverrides.data ?? []) as Array>).map( + (row) => ({ + episodeId: row.episode_id as string, + config: styleOverrideSchema.parse(row.config), + }), + ); + const sceneOverrides = ((scenesOverrides.data ?? []) as Array>).map( + (row) => { + const scene = firstRelation(row.scenes) as { episode_id?: string } | null; + return { + sceneId: row.scene_id as string, + episodeId: scene?.episode_id ?? '', + config: styleOverrideSchema.parse(row.config), + }; + }, + ); + return { presets, series, seasons, episodes, episodeOverrides, sceneOverrides }; +} + +interface SfxAudit { + valid: Set; + missing: boolean; + unlicensed: boolean; +} + +async function auditSfxAssets(db: SupabaseClient, owner: User, ids: string[]): Promise { + const unique = [...new Set(ids)]; + if (!unique.length) return { valid: new Set(), missing: false, unlicensed: false }; + const rows: Array> = []; + for (let index = 0; index < unique.length; index += 50) { + const { data, error } = await db + .from('audio_assets') + .select('id,license_status,commercial_allowed,social_allowed') + .eq('owner_id', owner.id) + .in('id', unique.slice(index, index + 50)); + if (error) + throw new StyleServiceError( + 503, + 'STYLE_ASSET_LOAD_FAILED', + 'Não foi possível validar os SFX.', + ); + rows.push(...(data ?? [])); + } + const present = new Set(rows.map((row) => row.id as string)); + const valid = new Set( + rows + .filter( + (row) => + row.license_status === 'VERIFIED' && + row.commercial_allowed === true && + row.social_allowed === true, + ) + .map((row) => row.id as string), + ); + return { + valid, + missing: unique.some((id) => !present.has(id)), + unlicensed: rows.some((row) => !valid.has(row.id as string)), + }; +} + +export async function resolveEpisodeStyleSnapshot( + db: SupabaseClient, + owner: User, + episodeId: string, +): Promise { + const { data: episode, error } = await db + .from('episodes') + .select('id,seasons(id,series_id)') + .eq('owner_id', owner.id) + .eq('id', episodeId) + .maybeSingle(); + if (error || !episode) + throw new StyleServiceError(404, 'STYLE_EPISODE_NOT_FOUND', 'Episódio não encontrado.'); + const season = firstRelation(episode.seasons) as { id?: string; series_id?: string } | null; + const seriesId = season?.series_id ?? null; + const seasonId = season?.id ?? null; + const [seriesPreset, seasonPreset, episodeOverride, scenesResult] = await Promise.all([ + seriesId ? loadPresetForScope(db, owner, 'SERIES', seriesId) : Promise.resolve(null), + seasonId ? loadPresetForScope(db, owner, 'SEASON', seasonId) : Promise.resolve(null), + db + .from('episode_style_overrides') + .select('config') + .eq('owner_id', owner.id) + .eq('episode_id', episodeId) + .maybeSingle(), + db + .from('scenes') + .select('id,scene_index') + .eq('owner_id', owner.id) + .eq('episode_id', episodeId) + .order('scene_index') + .limit(200), + ]); + if (episodeOverride.error || scenesResult.error) + throw new StyleServiceError(503, 'STYLE_LOAD_FAILED', 'Não foi possível carregar o estilo.'); + const sceneRows = (scenesResult.data ?? []).map((row) => ({ + id: row.id as string, + index: Number(row.scene_index), + })); + const sceneIds = sceneRows.map((scene) => scene.id); + const sceneOverrideRows: Array> = []; + for (let index = 0; index < sceneIds.length; index += 50) { + const { data, error } = await db + .from('scene_style_overrides') + .select('scene_id,config') + .eq('owner_id', owner.id) + .in('scene_id', sceneIds.slice(index, index + 50)); + if (error) + throw new StyleServiceError(503, 'STYLE_LOAD_FAILED', 'Não foi possível carregar o estilo.'); + sceneOverrideRows.push(...(data ?? [])); + } + const overridesByScene = new Map( + sceneOverrideRows.map((row) => [row.scene_id as string, styleOverrideSchema.parse(row.config)]), + ); + const layers: StyleLayer[] = [ + { source: 'SERIES', config: seriesPreset?.approved?.config ?? null }, + { source: 'SEASON', config: seasonPreset?.approved?.config ?? null }, + { + source: 'EPISODE', + config: episodeOverride.data ? styleOverrideSchema.parse(episodeOverride.data.config) : null, + }, + ]; + const resolved = resolveStyle(layers); + const resolvedScenes = sceneRows.flatMap((scene) => { + const override = overridesByScene.get(scene.id); + if (!override) return []; + const sceneResolved = resolveStyle([...layers, { source: 'SCENE', config: override }]); + return [ + { + sceneId: scene.id, + sceneIndex: scene.index, + config: sceneResolved.config, + sources: sceneResolved.sources, + }, + ]; + }); + const audit = await auditSfxAssets(db, owner, [ + ...resolved.config.sfxAssetIds, + ...resolvedScenes.flatMap((scene) => scene.config.sfxAssetIds), + ]); + const chosen = seasonPreset?.approved ?? seriesPreset?.approved ?? null; + const warnings: string[] = []; + if (!chosen) warnings.push('STYLE_PRESET_MISSING'); + if (audit.missing) warnings.push('STYLE_SFX_UNAVAILABLE'); + if (audit.unlicensed) warnings.push('STYLE_SFX_LICENSE'); + return { + presetId: + (seasonPreset?.approved + ? seasonPreset.id + : seriesPreset?.approved + ? seriesPreset.id + : null) ?? null, + presetRevision: chosen?.revision ?? null, + presetHash: chosen?.configHash ?? null, + scopeType: seasonPreset?.approved ? 'SEASON' : seriesPreset?.approved ? 'SERIES' : null, + scopeId: seasonPreset?.approved ? seasonId : seriesPreset?.approved ? seriesId : null, + config: withdrawInvalidSfx(resolved.config, audit.valid), + sources: resolved.sources, + scenes: resolvedScenes.map((scene) => ({ + ...scene, + config: withdrawInvalidSfx(scene.config, audit.valid), + })), + warnings, + capturedAt: new Date().toISOString(), + }; +} + +export async function exportStylePreset( + db: SupabaseClient, + owner: User, + presetId: string, +): Promise<{ + format: 'dif-studio-style-preset/v1'; + presetId: string; + scopeType: string; + scopeId: string; + name: string; + revision: number; + configHash: string; + config: StyleConfig; +}> { + const { data: preset, error } = await db + .from('style_presets') + .select('*') + .eq('owner_id', owner.id) + .eq('id', presetId) + .maybeSingle(); + if (error) + throw new StyleServiceError(503, 'STYLE_LOAD_FAILED', 'Não foi possível carregar o preset.'); + if (!preset) throw new StyleServiceError(404, 'STYLE_NOT_FOUND', 'Preset não encontrado.'); + const loaded = await loadPresetForScope( + db, + owner, + preset.scope_type as StyleScopeType, + preset.scope_id, + ); + const revision = loaded?.approved ?? loaded?.revisions[0] ?? null; + if (!revision) throw new StyleServiceError(404, 'STYLE_NOT_FOUND', 'O preset não tem revisões.'); + return { + format: 'dif-studio-style-preset/v1', + presetId: preset.id as string, + scopeType: preset.scope_type as string, + scopeId: preset.scope_id as string, + name: preset.name as string, + revision: revision.revision, + configHash: revision.configHash, + config: revision.config, + }; +} + +export async function importStylePreset(input: { + db: SupabaseClient; + adminDb: SupabaseClient | null; + owner: User; + payload: unknown; +}): Promise { + const parsed = styleImportSchema.safeParse(input.payload); + if (!parsed.success) + throw new StyleServiceError(400, 'STYLE_IMPORT_INVALID', 'JSON de estilo inválido.'); + const existing = await loadPresetForScope( + input.db, + input.owner, + parsed.data.scopeType, + parsed.data.scopeId, + ); + return ( + await saveStylePreset({ + db: input.db, + adminDb: input.adminDb, + owner: input.owner, + values: { + scopeType: parsed.data.scopeType, + scopeId: parsed.data.scopeId, + name: parsed.data.name, + expectedRevision: existing?.latestRevision ?? 0, + config: parsed.data.config, + status: 'DRAFT', + }, + }) + ).revision; +} + +export const STYLE_HASH_VERSION_EXPORT = STYLE_HASH_VERSION; diff --git a/src/lib/server/video-edit-plans.test.ts b/src/lib/server/video-edit-plans.test.ts new file mode 100644 index 00000000..a839a9ed --- /dev/null +++ b/src/lib/server/video-edit-plans.test.ts @@ -0,0 +1,82 @@ +import { describe, expect, it } from 'vitest'; +import { buildDefaultEditPlan } from '#lib/domain/video-edit-plan.js'; +import { DEFAULT_STYLE_CONFIG, STYLE_FIELDS } from '#lib/domain/style-bible.js'; +import { styleConfigSchema, type StyleSnapshot } from '#lib/schemas/style-bible.js'; +import { attachStyleSnapshot } from './video-edit-plans.js'; + +const episodeId = '11111111-1111-4111-8111-111111111111'; +const sceneId = '22222222-2222-4222-8222-222222222222'; +const assetId = '33333333-3333-4333-8333-333333333333'; + +function plan() { + return buildDefaultEditPlan({ + episodeId, + episodeRevisionNumber: 3, + durationMs: 90_000, + sceneDurationMs: 6_000, + scenes: [{ id: sceneId, sceneIndex: 1, startMs: 0, endMs: 6_000 }], + assets: [{ id: assetId, sceneId, assetVersion: 2, durationMs: 6_000 }], + }); +} + +function snapshot(overrides: Record = {}): StyleSnapshot { + return { + presetId: 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa', + presetRevision: 4, + presetHash: 'a'.repeat(64), + scopeType: 'SERIES', + scopeId: 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb', + config: styleConfigSchema.parse({ + ...DEFAULT_STYLE_CONFIG, + colorPresetId: 'cctv', + colorStrength: 0.65, + ...overrides, + }), + sources: Object.fromEntries(STYLE_FIELDS.map((field) => [field, 'SERIES'])), + scenes: [ + { + sceneId, + sceneIndex: 1, + config: styleConfigSchema.parse({ ...DEFAULT_STYLE_CONFIG, captionTemplate: 'horror' }), + sources: { captionTemplate: 'SCENE' }, + }, + ], + warnings: [], + capturedAt: '2026-11-20T12:00:00Z', + }; +} + +describe('attachStyleSnapshot', () => { + it('freezes the resolved style and injects color when the plan has none', () => { + const original = plan(); + const styled = attachStyleSnapshot(original, snapshot()); + expect(styled.styleBible).toMatchObject({ + presetId: 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa', + presetRevision: 4, + presetHash: 'a'.repeat(64), + }); + expect(styled.styleBible?.scenes?.[0]?.sources.captionTemplate).toBe('SCENE'); + expect(styled.color).toMatchObject({ presetId: 'cctv', presetVersion: 1, strength: 65 }); + expect(original.styleBible).toBeUndefined(); + expect(original.color).toBeUndefined(); + }); + + it('does not inject a neutral grade or overwrite an explicit plan color', () => { + expect( + attachStyleSnapshot(plan(), snapshot({ colorPresetId: 'neutral' })).color, + ).toBeUndefined(); + const explicit = { + ...plan(), + color: { + presetId: 'vhs_1987' as const, + presetVersion: 1 as const, + strength: 40, + referenceClipId: null, + overrides: [], + }, + }; + const styled = attachStyleSnapshot(explicit, snapshot()); + expect(styled.color).toEqual(explicit.color); + expect(styled.styleBible?.presetRevision).toBe(4); + }); +}); diff --git a/src/lib/server/video-edit-plans.ts b/src/lib/server/video-edit-plans.ts index 76a25176..a58198c6 100644 --- a/src/lib/server/video-edit-plans.ts +++ b/src/lib/server/video-edit-plans.ts @@ -15,6 +15,8 @@ import { ChoiceEndCardError, loadApprovedEndCardSnapshot, } from './choice-end-card.js'; +import { resolveEpisodeStyleSnapshot, StyleServiceError } from './style-bible.js'; +import type { StyleSnapshot } from '#lib/schemas/style-bible.js'; export class VideoEditPlanError extends Error { constructor( @@ -239,6 +241,23 @@ async function assertPlanAudioAssets( } } +export function attachStyleSnapshot(plan: VideoEditPlan, styleBible: StyleSnapshot): VideoEditPlan { + const styled = { ...plan, styleBible }; + if (!styled.color && styleBible.config.colorPresetId !== 'neutral') { + return { + ...styled, + color: { + presetId: styleBible.config.colorPresetId, + presetVersion: 1, + strength: Math.round(styleBible.config.colorStrength * 100), + referenceClipId: null, + overrides: [], + }, + }; + } + return styled; +} + export function validateForContext(plan: VideoEditPlan, context: EditPlanContext): VideoEditPlan { try { return validateEditPlan(plan, context); @@ -284,7 +303,16 @@ export async function saveVideoEditPlan(input: { throw cause; } } - const plan = validateForContext(linkedPlan, context); + let styledPlan: VideoEditPlan; + try { + const styleBible = await resolveEpisodeStyleSnapshot(input.db, input.owner, input.episodeId); + styledPlan = attachStyleSnapshot(linkedPlan, styleBible); + } catch (cause) { + if (cause instanceof StyleServiceError) + throw new VideoEditPlanError(cause.status, cause.code, cause.message); + throw cause; + } + const plan = validateForContext(styledPlan, context); await assertPlanAudioAssets(input.db, input.owner.id, plan); if (!input.adminDb) throw new VideoEditPlanError( diff --git a/src/routes/api/style/[presetId]/+server.ts b/src/routes/api/style/[presetId]/+server.ts new file mode 100644 index 00000000..a936e895 --- /dev/null +++ b/src/routes/api/style/[presetId]/+server.ts @@ -0,0 +1,31 @@ +import { error } from '@sveltejs/kit'; +import type { RequestHandler } from './$types'; +import { ownerDatabase } from '#lib/server/authorized.js'; +import { exportStylePreset, StyleServiceError } from '#lib/server/style-bible.js'; + +export const GET: RequestHandler = async (event) => { + const { db, owner } = ownerDatabase(event); + try { + const payload = await exportStylePreset(db, owner, event.params.presetId); + const download = event.url.searchParams.get('download') === '1'; + const filename = `dif-style-${ + payload.name + .toLowerCase() + .replace(/[^a-z0-9]+/g, '-') + .replace(/^-|-$/g, '') || 'preset' + }-v${payload.revision}.json`; + return new Response(JSON.stringify(payload, null, 2), { + headers: { + 'content-type': 'application/json; charset=utf-8', + 'cache-control': 'private, no-store', + 'content-disposition': `${download ? 'attachment' : 'inline'}; filename="${filename}"`, + 'x-content-type-options': 'nosniff', + }, + }); + } catch (cause) { + if (cause instanceof StyleServiceError) { + error(cause.status === 404 ? 404 : cause.status === 403 ? 403 : 503, cause.message); + } + throw cause; + } +}; diff --git a/src/routes/app/style/+page.server.ts b/src/routes/app/style/+page.server.ts new file mode 100644 index 00000000..d986c02c --- /dev/null +++ b/src/routes/app/style/+page.server.ts @@ -0,0 +1,353 @@ +import { fail, redirect } from '@sveltejs/kit'; +import type { Actions, PageServerLoad } from './$types'; +import { ownerDatabase, readFormText } from '#lib/server/authorized.js'; +import { createSupabaseAdminClient } from '#lib/server/supabase.js'; +import { + exportStylePreset, + importStylePreset, + loadStylePageContext, + resolveEpisodeStyleSnapshot, + saveEpisodeStyleOverride, + saveSceneStyleOverride, + saveStylePreset, + StyleServiceError, + type StylePreset, +} from '#lib/server/style-bible.js'; +import { + styleConfigSchema, + styleOverrideSchema, + type StyleConfig, + type StyleOverride, + type StyleScopeType, +} from '#lib/schemas/style-bible.js'; + +function messageFor(cause: unknown): { status: number; message: string } { + if (cause instanceof StyleServiceError) return { status: cause.status, message: cause.message }; + if (cause instanceof Error && cause.name === 'ZodError') + return { status: 400, message: 'Configuração de estilo inválida.' }; + return { status: 503, message: 'Não foi possível processar a bíblia audiovisual.' }; +} + +function rethrowRedirect(cause: unknown): void { + if (cause && typeof cause === 'object' && 'location' in cause) throw cause; +} + +function readNumber(form: FormData, key: string): number { + const value = Number(readFormText(form, key)); + return Number.isFinite(value) ? value : 0; +} + +function configFromForm(form: FormData): StyleConfig { + return styleConfigSchema.parse({ + schemaVersion: 1, + paletteBackground: readFormText(form, 'paletteBackground'), + paletteForeground: readFormText(form, 'paletteForeground'), + paletteAccent: readFormText(form, 'paletteAccent'), + paletteMuted: readFormText(form, 'paletteMuted'), + colorPresetId: readFormText(form, 'colorPresetId'), + colorStrength: readNumber(form, 'colorStrength') / 100, + fontFamily: readFormText(form, 'fontFamily'), + captionTemplate: readFormText(form, 'captionTemplate'), + captionSafeZone: readFormText(form, 'captionSafeZone'), + motion: readFormText(form, 'motion'), + reducedMotion: readFormText(form, 'reducedMotion') === 'on', + vhsIntensity: readNumber(form, 'vhsIntensity'), + sfxCategory: readFormText(form, 'sfxCategory'), + sfxAssetIds: readFormText(form, 'sfxAssetIds') + .split(',') + .map((value) => value.trim()) + .filter(Boolean), + voiceStyle: readFormText(form, 'voiceStyle'), + openingHookKind: readFormText(form, 'openingHookKind'), + coverTemplateId: readFormText(form, 'coverTemplateId'), + endCardTemplateId: readFormText(form, 'endCardTemplateId'), + ctaPrompt: readFormText(form, 'ctaPrompt'), + }); +} + +function overrideFromForm(form: FormData): StyleOverride { + const raw: Record = {}; + const stringFields = [ + 'paletteBackground', + 'paletteForeground', + 'paletteAccent', + 'paletteMuted', + 'colorPresetId', + 'fontFamily', + 'captionTemplate', + 'captionSafeZone', + 'motion', + 'sfxCategory', + 'voiceStyle', + 'openingHookKind', + 'coverTemplateId', + 'endCardTemplateId', + 'ctaPrompt', + ]; + for (const field of stringFields) { + const value = readFormText(form, field); + if (value) raw[field] = value; + } + const strength = readFormText(form, 'colorStrength'); + if (strength) raw.colorStrength = Number(strength) / 100; + const vhs = readFormText(form, 'vhsIntensity'); + if (vhs) raw.vhsIntensity = Number(vhs); + if (readFormText(form, 'sfxOverride') === 'on') { + raw.sfxAssetIds = readFormText(form, 'sfxAssetIds') + .split(',') + .map((value) => value.trim()) + .filter(Boolean); + } + if (readFormText(form, 'reducedMotion') === 'on') raw.reducedMotion = true; + return styleOverrideSchema.parse(raw); +} + +function presetFor(presets: StylePreset[], id: string | null): StylePreset | null { + return id ? (presets.find((preset) => preset.id === id) ?? null) : null; +} + +function redirectFor(form: FormData, suffix: string): never { + const scopeType = readFormText(form, 'scopeType') || 'SERIES'; + const scopeId = readFormText(form, 'scopeId'); + const episodeId = readFormText(form, 'episodeId'); + redirect( + 303, + `/app/style?scopeType=${scopeType}&scopeId=${scopeId}${episodeId ? `&episodeId=${episodeId}` : ''}&${suffix}`, + ); +} + +export const load: PageServerLoad = async (event) => { + const { db, owner } = ownerDatabase(event); + const context = await loadStylePageContext(db, owner); + const scopeType = ( + event.url.searchParams.get('scopeType') === 'SEASON' ? 'SEASON' : 'SERIES' + ) as StyleScopeType; + const requestedScopeId = event.url.searchParams.get('scopeId'); + const fallbackScopeId = + scopeType === 'SERIES' ? (context.series[0]?.id ?? '') : (context.seasons[0]?.id ?? ''); + const scopeId = requestedScopeId || fallbackScopeId; + const selectedPreset = + context.presets.find( + (preset) => preset.scopeType === scopeType && preset.scopeId === scopeId, + ) ?? null; + const episodeId = event.url.searchParams.get('episodeId') || context.episodes[0]?.id || ''; + let preview = null; + let previewError: string | null = null; + let scenes: Array<{ id: string; index: number }> = []; + if (episodeId) { + try { + preview = await resolveEpisodeStyleSnapshot(db, owner, episodeId); + const { data, error: scenesError } = await db + .from('scenes') + .select('id,scene_index') + .eq('owner_id', owner.id) + .eq('episode_id', episodeId) + .order('scene_index') + .limit(60); + if (scenesError) throw scenesError; + scenes = (data ?? []).map((row) => ({ + id: row.id as string, + index: Number(row.scene_index), + })); + } catch (cause) { + preview = null; + previewError = + cause instanceof StyleServiceError + ? cause.message + : 'Não foi possível resolver a herança de estilo deste episódio.'; + } + } + const notice = event.url.searchParams.get('saved') ? event.url.searchParams.get('saved') : null; + const selectedSceneId = event.url.searchParams.get('sceneId') || (scenes[0]?.id ?? ''); + return { + context, + scopeType, + scopeId, + selectedPreset, + episodeId, + selectedSceneId, + preview, + previewError, + scenes, + notice, + error: null, + }; +}; + +export const actions: Actions = { + save: async (event) => { + const { db, owner } = ownerDatabase(event); + const form = await event.request.formData(); + try { + await saveStylePreset({ + db, + adminDb: createSupabaseAdminClient(), + owner, + values: { + scopeType: readFormText(form, 'scopeType'), + scopeId: readFormText(form, 'scopeId'), + name: readFormText(form, 'name'), + expectedRevision: Number(readFormText(form, 'expectedRevision')), + config: configFromForm(form), + status: 'DRAFT', + }, + }); + redirectFor(form, 'saved=preset'); + } catch (cause) { + rethrowRedirect(cause); + const info = messageFor(cause); + return fail(info.status, { message: info.message }); + } + }, + approve: async (event) => { + const { db, owner } = ownerDatabase(event); + const form = await event.request.formData(); + try { + const context = await loadStylePageContext(db, owner); + const preset = presetFor(context.presets, readFormText(form, 'presetId')); + if (!preset) throw new StyleServiceError(404, 'STYLE_NOT_FOUND', 'Preset não encontrado.'); + const latest = preset.revisions[0]; + if (!latest) throw new StyleServiceError(404, 'STYLE_NOT_FOUND', 'Preset sem revisão.'); + await saveStylePreset({ + db, + adminDb: createSupabaseAdminClient(), + owner, + values: { + scopeType: preset.scopeType, + scopeId: preset.scopeId, + name: preset.name, + expectedRevision: preset.latestRevision, + config: latest.config, + status: 'APPROVED', + }, + }); + redirectFor(form, 'saved=approved'); + } catch (cause) { + rethrowRedirect(cause); + const info = messageFor(cause); + return fail(info.status, { message: info.message }); + } + }, + restore: async (event) => { + const { db, owner } = ownerDatabase(event); + const form = await event.request.formData(); + try { + const context = await loadStylePageContext(db, owner); + const preset = presetFor(context.presets, readFormText(form, 'presetId')); + const revisionNumber = Number(readFormText(form, 'revision')); + const revision = preset?.revisions.find((entry) => entry.revision === revisionNumber); + if (!preset || !revision) + throw new StyleServiceError(404, 'STYLE_NOT_FOUND', 'Revisão não encontrada.'); + await saveStylePreset({ + db, + adminDb: createSupabaseAdminClient(), + owner, + values: { + scopeType: preset.scopeType, + scopeId: preset.scopeId, + name: preset.name, + expectedRevision: preset.latestRevision, + config: revision.config, + status: 'DRAFT', + }, + }); + redirectFor(form, 'saved=restored'); + } catch (cause) { + rethrowRedirect(cause); + const info = messageFor(cause); + return fail(info.status, { message: info.message }); + } + }, + duplicate: async (event) => { + const { db, owner } = ownerDatabase(event); + const form = await event.request.formData(); + try { + const source = await exportStylePreset(db, owner, readFormText(form, 'presetId')); + await importStylePreset({ + db, + adminDb: createSupabaseAdminClient(), + owner, + payload: { + ...source, + name: readFormText(form, 'targetName') || `${source.name} (cópia)`, + scopeType: readFormText(form, 'targetScopeType'), + scopeId: readFormText(form, 'targetScopeId'), + }, + }); + redirectFor(form, 'saved=duplicated'); + } catch (cause) { + rethrowRedirect(cause); + const info = messageFor(cause); + return fail(info.status, { message: info.message }); + } + }, + import: async (event) => { + const { db, owner } = ownerDatabase(event); + const form = await event.request.formData(); + let payload: Record; + try { + payload = JSON.parse(readFormText(form, 'json')) as Record; + } catch { + return fail(400, { message: 'JSON de estilo inválido.' }); + } + try { + await importStylePreset({ + db, + adminDb: createSupabaseAdminClient(), + owner, + payload: { + ...payload, + name: readFormText(form, 'name') || payload.name, + scopeType: readFormText(form, 'scopeType'), + scopeId: readFormText(form, 'scopeId'), + }, + }); + redirectFor(form, 'saved=imported'); + } catch (cause) { + rethrowRedirect(cause); + const info = messageFor(cause); + return fail(info.status, { message: info.message }); + } + }, + override: async (event) => { + const { db, owner } = ownerDatabase(event); + const form = await event.request.formData(); + const episodeId = readFormText(form, 'episodeId'); + if (!episodeId) return fail(400, { message: 'Episódio inválido.' }); + try { + await saveEpisodeStyleOverride({ + db, + adminDb: createSupabaseAdminClient(), + owner, + episodeId, + config: overrideFromForm(form), + }); + redirect(303, `/app/style?episodeId=${episodeId}&saved=override`); + } catch (cause) { + rethrowRedirect(cause); + const info = messageFor(cause); + return fail(info.status, { message: info.message }); + } + }, + sceneOverride: async (event) => { + const { db, owner } = ownerDatabase(event); + const form = await event.request.formData(); + const sceneId = readFormText(form, 'sceneId'); + const episodeId = readFormText(form, 'episodeId'); + if (!sceneId) return fail(400, { message: 'Cena inválida.' }); + try { + await saveSceneStyleOverride({ + db, + adminDb: createSupabaseAdminClient(), + owner, + sceneId, + config: overrideFromForm(form), + }); + redirect(303, `/app/style?episodeId=${episodeId}&saved=scene-override`); + } catch (cause) { + rethrowRedirect(cause); + const info = messageFor(cause); + return fail(info.status, { message: info.message }); + } + }, +}; diff --git a/src/routes/app/style/+page.svelte b/src/routes/app/style/+page.svelte new file mode 100644 index 00000000..63504e26 --- /dev/null +++ b/src/routes/app/style/+page.svelte @@ -0,0 +1,744 @@ + + +Estilo · DIF Studio + + + +{#if data.notice} +

{noticeText(data.notice)}

+{/if} +{#if form?.message}{/if} + +
+ + + +
+ +
+
+
+

{scopeName(data.scopeType, data.scopeId)}

+ {#if selectedPreset} + + {approved ? `aprovado v${approved.revision}` : 'sem versão aprovada'} + + {:else} + sem preset + {/if} +
+ {#if selectedPreset} +

+ {selectedPreset.name} · {selectedPreset.revisions.length} revisão(ões) · hash + {latest?.configHash.slice(0, 12) ?? '—'} +

+ {#if !approved} +

+ Este preset só tem DRAFT. Episódios herdam do escopo pai até você aprovar uma revisão. +

+ {/if} + {:else} +

+ Nenhum preset nesta camada. Salvar cria a revisão 1 como DRAFT; aprovar publica a herança. +

+ {/if} + {#key `${data.scopeType}:${data.scopeId}:${latest?.revision ?? 0}`} + + {/key} +
+ +
+
+

Prévia efetiva

+ {#if data.preview}{data.preview.sources ? 'resolvido' : ''}{/if} +
+
+ + + +
+ {#if data.preview} +
+ + A casa não responde +

{data.preview.config.ctaPrompt}

+ + {data.preview.config.captionTemplate} · {data.preview.config.captionSafeZone} · + {data.preview.config.motion} · {data.preview.config.colorPresetId} · + {Math.round(data.preview.config.colorStrength * 100)}% + +
+ {#each data.preview.warnings as warning (warning)} +

{warningLabels[warning] ?? warning}

+ {/each} +
+
+
Cor
+
+ {data.preview.config.colorPresetId} · {Math.round( + data.preview.config.colorStrength * 100, + )}% +
+
+
+
SFX
+
+ {data.preview.config.sfxCategory} · {data.preview.config.sfxAssetIds.length} asset(s) +
+
+
+
Voz
+
{data.preview.config.voiceStyle}
+
+
+
Abertura
+
{data.preview.config.openingHookKind}
+
+
+
Capa
+
+ {data.preview.config.coverTemplateId} · + abrir capas +
+
+
+
Final A/B
+
+ {data.preview.config.endCardTemplateId} · + abrir final +
+
+
+
CTA
+
{data.preview.config.ctaPrompt}
+
+
+
+ {#each STYLE_FIELDS as field (field)} + {fieldLabels[field] ?? field} + {sourceLabels[data.preview.sources[field]] ?? data.preview.sources[field]} + {/each} +
+ {#if data.preview.scenes?.length} +
+ {data.preview.scenes.length} cena(s) com override congelado +
    + {#each data.preview.scenes as scene (scene.sceneId)} +
  • + Cena {scene.sceneIndex}: {scene.config.captionTemplate} / + {scene.config.captionSafeZone} · {scene.config.motion} · + {sourceLabels[scene.sources.captionTemplate] ?? scene.sources.captionTemplate} +
  • + {/each} +
+
+ {/if} +

+ Preset {data.preview.presetId + ? `${data.preview.presetId.slice(0, 8)} @ v${data.preview.presetRevision}` + : 'ausente'}. O snapshot é gravado no plano ao salvar a timeline; editar o preset depois + não muda planos antigos. +

+ {:else} +

+ {data.previewError ?? 'Selecione um episódio para resolver a herança.'} +

+ {/if} +
+
+ +{#if selectedPreset && selectedPreset.revisions.length} +
+

Revisões do preset

+
+ {#each selectedPreset.revisions as revision (revision.id)} +
+
+ v{revision.revision} · {revision.status} + {new Date(revision.createdAt).toLocaleString('pt-BR')} +
+

+ {revision.config.fontFamily} · {revision.config.captionTemplate} · + {revision.config.motion} · {revision.config.sfxCategory} · + {revision.config.voiceStyle} +

+ {revision.configHash.slice(0, 16)} +
+ {#if revision.status !== 'APPROVED'} +
+ + + + + +
+ {/if} + {#if revision.revision !== selectedPreset.latestRevision} +
+ + + + + + +
+ {/if} + {#if approved?.id === revision.id} + JSON + baixar + {/if} +
+
+ {/each} +
+
+{/if} + +{#if data.episodeId} +
+
+
+

Override do episódio

+ {#if episodeOverride}ativo{:else}herdando{/if} +
+

+ {selectedEpisode + ? `${selectedEpisode.seriesTitle} · E${selectedEpisode.number} — ${selectedEpisode.title}` + : 'Episódio'} + vence a série e a temporada, campo por campo. +

+ {#key `episode:${data.episodeId}:${JSON.stringify(episodeOverride?.config ?? {})}`} + + {/key} +
+ +
+
+

Override da cena

+ {#if sceneOverride}ativo{:else}sem override{/if} +
+ {#if data.scenes.length} +
+ + + + +
+ {#key `scene:${data.selectedSceneId}:${JSON.stringify(sceneOverride?.config ?? {})}`} + + {/key} +

+ A cena {selectedScene?.index} vence todas as outras camadas apenas neste campo; o preset da + série permanece intacto. Um override vazio limpa a camada. +

+ {:else} +

Este episódio ainda não tem cenas.

+ {/if} +
+
+{/if} + +
+
+

Importar preset

+
+ + + + + +
+
+ +
+

Duplicar para outro escopo

+ {#if selectedPreset} +
+ + + + + +
+ + +
+

+ Escolha um destino do tipo correspondente. O preset entra como DRAFT no escopo escolhido; + a aprovação continua explícita. +

+ +
+ {:else} +

Abra um escopo com preset para duplicar.

+ {/if} +
+
+ + diff --git a/src/routes/app/style/StyleConfigFields.svelte b/src/routes/app/style/StyleConfigFields.svelte new file mode 100644 index 00000000..2f37a921 --- /dev/null +++ b/src/routes/app/style/StyleConfigFields.svelte @@ -0,0 +1,524 @@ + + +{#if mode === 'full'} +
+ + + + + +
+ + + + +
+
+ + +
+
+ + + +
+
+ + +
+ +
+ + +
+
+ + +
+
+ + +
+ +
+ A casa não responde + {draft.ctaPrompt} + + {draft.motion} · {draft.captionTemplate} · {draft.sfxCategory} · VHS {draft.vhsIntensity} + +
+ +
+{:else} +
+ + + + {#if mode === 'scene'}{/if} +

+ Deixe um campo vazio para herdar da camada superior. Enviar tudo vazio limpa o override. +

+
+ + + + +
+
+ + +
+
+ + + +
+
+ + +
+ +
+ + +
+ +
+ + +
+
+ + +
+ + +
+{/if} + + diff --git a/src/routes/app/style/style-actions.test.ts b/src/routes/app/style/style-actions.test.ts new file mode 100644 index 00000000..e8f3b870 --- /dev/null +++ b/src/routes/app/style/style-actions.test.ts @@ -0,0 +1,223 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +const style = vi.hoisted(() => { + class StyleServiceError extends Error { + constructor( + readonly status: number, + readonly code: string, + message: string, + ) { + super(message); + this.name = 'StyleServiceError'; + } + } + return { + StyleServiceError, + exportStylePreset: vi.fn(), + importStylePreset: vi.fn(), + loadStylePageContext: vi.fn(), + resolveEpisodeStyleSnapshot: vi.fn(), + saveEpisodeStyleOverride: vi.fn(), + saveSceneStyleOverride: vi.fn(), + saveStylePreset: vi.fn(), + }; +}); +const authorized = vi.hoisted(() => ({ + ownerDatabase: vi.fn(), + readFormText: (form: FormData, key: string) => { + const value = form.get(key); + return typeof value === 'string' ? value : ''; + }, +})); + +vi.mock('#lib/server/style-bible.js', () => style); +vi.mock('#lib/server/authorized.js', () => authorized); +vi.mock('#lib/server/supabase.js', () => ({ createSupabaseAdminClient: () => ({}) })); + +import { actions } from './+page.server.js'; + +const scopeId = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa'; +const episodeId = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb'; +const sceneId = 'cccccccc-cccc-4ccc-8ccc-cccccccccccc'; +const presetId = 'dddddddd-dddd-4ddd-8ddd-dddddddddddd'; +const config = { + schemaVersion: 1, + paletteBackground: '#08090b', + paletteForeground: '#e8e2d6', + paletteAccent: '#b6ff9a', + paletteMuted: '#8a8a8a', + colorPresetId: 'neutral', + colorStrength: 0.8, + fontFamily: 'sans', + captionTemplate: 'clean', + captionSafeZone: 'tiktok', + motion: 'restrained', + reducedMotion: false, + vhsIntensity: 1, + sfxCategory: 'none', + sfxAssetIds: [], + voiceStyle: 'neutral', + openingHookKind: 'none', + coverTemplateId: 'noir', + endCardTemplateId: 'doors', + ctaPrompt: 'Comente A ou B', +}; + +function event(fields: Record) { + const form = new FormData(); + for (const [key, value] of Object.entries(fields)) form.set(key, value); + return { + request: new Request('http://localhost/app/style?/action', { method: 'POST', body: form }), + url: new URL('http://localhost/app/style'), + } as never; +} + +function configFields(overrides: Record = {}) { + return { + scopeType: 'SERIES', + scopeId, + episodeId, + name: 'Noir', + expectedRevision: '0', + paletteBackground: '#08090b', + paletteForeground: '#e8e2d6', + paletteAccent: '#b6ff9a', + paletteMuted: '#8a8a8a', + colorPresetId: 'neutral', + colorStrength: '80', + fontFamily: 'sans', + captionTemplate: 'clean', + captionSafeZone: 'tiktok', + motion: 'restrained', + vhsIntensity: '1', + sfxCategory: 'none', + sfxAssetIds: '', + voiceStyle: 'neutral', + openingHookKind: 'none', + coverTemplateId: 'noir', + endCardTemplateId: 'doors', + ctaPrompt: 'Comente A ou B', + ...overrides, + }; +} + +describe('style page actions', () => { + beforeEach(() => { + vi.clearAllMocks(); + authorized.ownerDatabase.mockReturnValue({ db: {}, owner: { id: 'owner-id' } }); + style.saveStylePreset.mockResolvedValue({ revision: 1, presetId: null }); + style.saveEpisodeStyleOverride.mockResolvedValue(undefined); + style.saveSceneStyleOverride.mockResolvedValue(undefined); + style.importStylePreset.mockResolvedValue(1); + }); + + it('saves a full preset with parsed numbers and redirects to the scope', async () => { + await expect( + (actions.save as (event: never) => Promise)(event(configFields())), + ).rejects.toMatchObject({ + status: 303, + location: `/app/style?scopeType=SERIES&scopeId=${scopeId}&episodeId=${episodeId}&saved=preset`, + }); + expect(style.saveStylePreset).toHaveBeenCalledWith( + expect.objectContaining({ + values: expect.objectContaining({ + scopeType: 'SERIES', + scopeId, + name: 'Noir', + expectedRevision: 0, + status: 'DRAFT', + config: expect.objectContaining({ + colorStrength: 0.8, + vhsIntensity: 1, + sfxAssetIds: [], + }), + }), + }), + ); + }); + + it('keeps an episode override sparse so unspecified fields inherit', async () => { + await expect( + (actions.override as (event: never) => Promise)( + event({ episodeId, captionTemplate: 'horror', motion: 'kinetic' }), + ), + ).rejects.toMatchObject({ status: 303, location: expect.stringContaining('saved=override') }); + expect(style.saveEpisodeStyleOverride).toHaveBeenCalledWith( + expect.objectContaining({ + episodeId, + config: { captionTemplate: 'horror', motion: 'kinetic' }, + }), + ); + }); + + it('lets a scene override replace the SFX list with an explicit empty list', async () => { + await expect( + (actions.sceneOverride as (event: never) => Promise)( + event({ episodeId, sceneId, sfxOverride: 'on', sfxAssetIds: '' }), + ), + ).rejects.toMatchObject({ status: 303 }); + expect(style.saveSceneStyleOverride).toHaveBeenCalledWith( + expect.objectContaining({ sceneId, config: { sfxAssetIds: [] } }), + ); + }); + + it('approves the latest revision with optimistic concurrency', async () => { + style.loadStylePageContext.mockResolvedValue({ + presets: [ + { + id: presetId, + scopeType: 'SERIES', + scopeId, + name: 'Noir', + latestRevision: 4, + revisions: [{ revision: 4, status: 'DRAFT', config }], + approved: null, + }, + ], + series: [], + seasons: [], + episodes: [], + episodeOverrides: [], + sceneOverrides: [], + }); + await expect( + (actions.approve as (event: never) => Promise)( + event({ presetId, scopeType: 'SERIES', scopeId, episodeId }), + ), + ).rejects.toMatchObject({ status: 303 }); + expect(style.saveStylePreset).toHaveBeenCalledWith( + expect.objectContaining({ + values: expect.objectContaining({ + expectedRevision: 4, + status: 'APPROVED', + config, + }), + }), + ); + }); + + it('rejects malformed import JSON with a readable 400 before any write', async () => { + const result = (await (actions.import as (event: never) => Promise)( + event({ + json: '{"format":', + scopeType: 'SERIES', + scopeId, + episodeId, + }), + )) as { status: number; data: { message: string } }; + expect(result.status).toBe(400); + expect(result.data.message).toContain('JSON'); + expect(style.importStylePreset).not.toHaveBeenCalled(); + }); + + it('surfaces a stale revision conflict instead of redirecting', async () => { + style.saveStylePreset.mockRejectedValueOnce( + new style.StyleServiceError(409, 'STYLE_REVISION_CONFLICT', 'Recarregue antes de salvar.'), + ); + const result = (await (actions.save as (event: never) => Promise)( + event(configFields({ expectedRevision: '2' })), + )) as { status: number; data: { message: string } }; + expect(result.status).toBe(409); + expect(result.data.message).toBe('Recarregue antes de salvar.'); + }); +}); diff --git a/src/routes/app/timeline/+page.server.ts b/src/routes/app/timeline/+page.server.ts index cdf19551..8b44302c 100644 --- a/src/routes/app/timeline/+page.server.ts +++ b/src/routes/app/timeline/+page.server.ts @@ -18,6 +18,8 @@ import { savePlanFromForm } from '#lib/server/plan-actions.js'; import { EditPlanError } from '#lib/domain/video-edit-plan.js'; import { loadVoicePlan } from '#lib/server/narration.js'; import { listAudioAssets } from '#lib/server/audio-library.js'; +import { resolveEpisodeStyleSnapshot } from '#lib/server/style-bible.js'; +import { styleSnapshotDrift } from '#lib/domain/style-bible.js'; import type { AudioAsset } from '#lib/schemas/audio-library.js'; function messageFor(cause: unknown): { status: number; message: string } { @@ -55,6 +57,7 @@ export const load: PageServerLoad = async (event) => { context: null, planError: null, planStale: false, + styleDrift: null, renderJobs: [], narration: null, audioAssets: [], @@ -72,6 +75,23 @@ export const load: PageServerLoad = async (event) => { planError = cause instanceof Error ? cause.message : 'Não foi possível criar o plano.'; } } + let styleDrift: ReturnType | null = null; + if (stored.plan?.plan.styleBible) { + try { + const currentStyle = await resolveEpisodeStyleSnapshot(db, owner, selectedEpisode.id); + styleDrift = styleSnapshotDrift(stored.plan.plan.styleBible, currentStyle); + } catch { + styleDrift = { + stale: true, + capturedRevision: stored.plan.plan.styleBible.presetRevision, + currentRevision: null, + capturedHash: stored.plan.plan.styleBible.presetHash, + currentHash: null, + configChanged: false, + scenesChanged: false, + }; + } + } let renderJobs: RenderJob[] = []; try { renderJobs = await listRenderJobs({ db, owner, episodeId: selectedEpisode.id }); @@ -132,6 +152,7 @@ export const load: PageServerLoad = async (event) => { planStale: Boolean( stored.plan && plan && plan.episodeRevisionNumber !== context.episodeRevisionNumber, ), + styleDrift, versions: stored.versions, storedPlan: stored.plan ? { @@ -155,6 +176,7 @@ export const load: PageServerLoad = async (event) => { context: null, planError: errorInfo.message, planStale: false, + styleDrift: null, renderJobs: [], narration: null, audioAssets: [], diff --git a/src/routes/app/timeline/+page.svelte b/src/routes/app/timeline/+page.svelte index defd74c4..9f34c2e0 100644 --- a/src/routes/app/timeline/+page.svelte +++ b/src/routes/app/timeline/+page.svelte @@ -479,6 +479,17 @@ {/if} + {#if data.styleDrift?.stale} +
+

+ O plano congela o estilo na revisão + {data.styleDrift.capturedRevision ?? 'ausente'}; a série/temporada está na revisão + {data.styleDrift.currentRevision ?? 'indisponível'}. Render e export continuam usando o + snapshot congelado. Salvar o plano aplica o estilo atual como uma nova versão (opt-in). +

+
+ {/if} + {#if editError} {/if} diff --git a/supabase/migrations/20261120130000_v2_wo021_style_bible.sql b/supabase/migrations/20261120130000_v2_wo021_style_bible.sql new file mode 100644 index 00000000..d770e5dc --- /dev/null +++ b/supabase/migrations/20261120130000_v2_wo021_style_bible.sql @@ -0,0 +1,232 @@ +-- V2 WO-021: versioned audiovisual style bibles for series/seasons plus +-- owner-scoped episode and scene overrides. Configs are allowlisted enums and +-- IDs; no font files, shell commands, URLs or arbitrary filter strings. + +create table public.style_presets ( + id uuid primary key default gen_random_uuid(), + owner_id uuid not null, + scope_type text not null check (scope_type in ('SERIES', 'SEASON')), + scope_id uuid not null, + name text not null check (char_length(btrim(name)) between 1 and 80), + created_at timestamptz not null default now(), + updated_at timestamptz not null default now(), + unique (owner_id, id), + unique (owner_id, scope_type, scope_id) +); + +create table public.style_preset_revisions ( + id uuid primary key default gen_random_uuid(), + owner_id uuid not null, + preset_id uuid not null, + revision_number integer not null check (revision_number between 1 and 10000), + config jsonb not null check (jsonb_typeof(config) = 'object'), + config_hash text not null check (config_hash ~ '^[0-9a-f]{64}$'), + hash_version integer not null default 1 check (hash_version = 1), + status text not null default 'DRAFT' check (status in ('DRAFT', 'APPROVED')), + created_at timestamptz not null default now(), + unique (owner_id, preset_id, revision_number), + unique (owner_id, id), + foreign key (owner_id, preset_id) references public.style_presets (owner_id, id) on delete restrict +); + +create table public.episode_style_overrides ( + episode_id uuid primary key, + owner_id uuid not null, + config jsonb not null check (jsonb_typeof(config) = 'object'), + created_at timestamptz not null default now(), + updated_at timestamptz not null default now(), + unique (owner_id, episode_id), + foreign key (owner_id, episode_id) references public.episodes (owner_id, id) on delete restrict +); + +create table public.scene_style_overrides ( + scene_id uuid primary key, + owner_id uuid not null, + config jsonb not null check (jsonb_typeof(config) = 'object'), + created_at timestamptz not null default now(), + updated_at timestamptz not null default now(), + unique (owner_id, scene_id), + foreign key (owner_id, scene_id) references public.scenes (owner_id, id) on delete restrict +); + +create index style_preset_revisions_by_preset + on public.style_preset_revisions (owner_id, preset_id, revision_number desc); + +alter table public.style_presets enable row level security; +alter table public.style_presets force row level security; +alter table public.style_preset_revisions enable row level security; +alter table public.style_preset_revisions force row level security; +alter table public.episode_style_overrides enable row level security; +alter table public.episode_style_overrides force row level security; +alter table public.scene_style_overrides enable row level security; +alter table public.scene_style_overrides force row level security; + +revoke all on table public.style_presets from public, anon, authenticated; +revoke all on table public.style_preset_revisions from public, anon, authenticated; +revoke all on table public.episode_style_overrides from public, anon, authenticated; +revoke all on table public.scene_style_overrides from public, anon, authenticated; + +grant select on table public.style_presets to authenticated; +grant select on table public.style_preset_revisions to authenticated; +grant select on table public.episode_style_overrides to authenticated; +grant select on table public.scene_style_overrides to authenticated; +grant select, insert, update, delete on table public.style_presets to service_role; +grant select, insert, update, delete on table public.style_preset_revisions to service_role; +grant select, insert, update, delete on table public.episode_style_overrides to service_role; +grant select, insert, update, delete on table public.scene_style_overrides to service_role; + +create policy owner_select on public.style_presets for select to authenticated + using (owner_id = (select auth.uid()) and (select auth.jwt() -> 'app_metadata' ->> 'dif_studio_owner') = 'true'); +create policy owner_select on public.style_preset_revisions for select to authenticated + using (owner_id = (select auth.uid()) and (select auth.jwt() -> 'app_metadata' ->> 'dif_studio_owner') = 'true'); +create policy owner_select on public.episode_style_overrides for select to authenticated + using (owner_id = (select auth.uid()) and (select auth.jwt() -> 'app_metadata' ->> 'dif_studio_owner') = 'true'); +create policy owner_select on public.scene_style_overrides for select to authenticated + using (owner_id = (select auth.uid()) and (select auth.jwt() -> 'app_metadata' ->> 'dif_studio_owner') = 'true'); + +create or replace function public.reject_style_revision_mutation() +returns trigger language plpgsql set search_path = pg_catalog, public +as $$ +begin + if current_setting('dif.style_prune', true) = 'on' and tg_op = 'DELETE' then + return old; + end if; + raise exception 'style_revision_is_immutable' using errcode = '55000'; +end; +$$; + +create trigger style_preset_revisions_immutable + before update or delete on public.style_preset_revisions + for each row execute function public.reject_style_revision_mutation(); + +create or replace function public.save_style_preset_revision( + p_owner_id uuid, + p_scope_type text, + p_scope_id uuid, + p_name text, + p_expected_revision integer, + p_config jsonb, + p_config_hash text, + p_status text default 'DRAFT' +) +returns integer +language plpgsql security definer set search_path = pg_catalog, public +as $$ +declare + v_preset public.style_presets; + v_latest integer; + v_revision integer; +begin + if p_owner_id is null or p_scope_id is null then + raise exception 'owner_auth_required' using errcode = '42501'; + end if; + if p_scope_type not in ('SERIES', 'SEASON') then + raise exception 'style_scope_invalid' using errcode = '23514'; + end if; + if char_length(btrim(coalesce(p_name, ''))) not between 1 and 80 + or p_config_hash !~ '^[0-9a-f]{64}$' + or jsonb_typeof(p_config) is distinct from 'object' + or p_status not in ('DRAFT', 'APPROVED') + or p_expected_revision is null or p_expected_revision < 0 then + raise exception 'style_revision_invalid' using errcode = '23514'; + end if; + if p_scope_type = 'SERIES' then + if not exists (select 1 from public.series s where s.owner_id = p_owner_id and s.id = p_scope_id) then + raise exception 'style_scope_not_found' using errcode = 'P0002'; + end if; + else + if not exists (select 1 from public.seasons s where s.owner_id = p_owner_id and s.id = p_scope_id) then + raise exception 'style_scope_not_found' using errcode = 'P0002'; + end if; + end if; + select * into v_preset from public.style_presets p + where p.owner_id = p_owner_id and p.scope_type = p_scope_type and p.scope_id = p_scope_id; + if not found then + insert into public.style_presets (owner_id, scope_type, scope_id, name) + values (p_owner_id, p_scope_type, p_scope_id, btrim(p_name)) + returning * into v_preset; + else + update public.style_presets + set name = btrim(p_name), updated_at = now() + where id = v_preset.id and owner_id = p_owner_id + returning * into v_preset; + end if; + select coalesce(max(r.revision_number), 0) into v_latest + from public.style_preset_revisions r + where r.owner_id = p_owner_id and r.preset_id = v_preset.id; + if v_latest <> p_expected_revision then + raise exception 'style_revision_conflict' using errcode = '40001'; + end if; + v_revision := v_latest + 1; + insert into public.style_preset_revisions ( + owner_id, preset_id, revision_number, config, config_hash, hash_version, status + ) values ( + p_owner_id, v_preset.id, v_revision, p_config, p_config_hash, 1, p_status + ); + return v_revision; +end; +$$; + +create or replace function public.save_episode_style_override( + p_owner_id uuid, + p_episode_id uuid, + p_config jsonb +) +returns void +language plpgsql security definer set search_path = pg_catalog, public +as $$ +begin + if p_owner_id is null or p_episode_id is null then + raise exception 'owner_auth_required' using errcode = '42501'; + end if; + if jsonb_typeof(p_config) is distinct from 'object' then + raise exception 'style_override_invalid' using errcode = '23514'; + end if; + if not exists (select 1 from public.episodes e where e.owner_id = p_owner_id and e.id = p_episode_id) then + raise exception 'episode_not_found' using errcode = 'P0002'; + end if; + insert into public.episode_style_overrides (episode_id, owner_id, config) + values (p_episode_id, p_owner_id, p_config) + on conflict (episode_id) do update + set config = excluded.config, owner_id = excluded.owner_id, updated_at = now(); +end; +$$; + +create or replace function public.save_scene_style_override( + p_owner_id uuid, + p_scene_id uuid, + p_config jsonb +) +returns void +language plpgsql security definer set search_path = pg_catalog, public +as $$ +begin + if p_owner_id is null or p_scene_id is null then + raise exception 'owner_auth_required' using errcode = '42501'; + end if; + if jsonb_typeof(p_config) is distinct from 'object' then + raise exception 'style_override_invalid' using errcode = '23514'; + end if; + if not exists (select 1 from public.scenes s where s.owner_id = p_owner_id and s.id = p_scene_id) then + raise exception 'style_scene_not_found' using errcode = 'P0002'; + end if; + insert into public.scene_style_overrides (scene_id, owner_id, config) + values (p_scene_id, p_owner_id, p_config) + on conflict (scene_id) do update + set config = excluded.config, owner_id = excluded.owner_id, updated_at = now(); +end; +$$; + +revoke all on function public.save_style_preset_revision(uuid, text, uuid, text, integer, jsonb, text, text) from public, anon, authenticated; +revoke all on function public.save_episode_style_override(uuid, uuid, jsonb) from public, anon, authenticated; +revoke all on function public.save_scene_style_override(uuid, uuid, jsonb) from public, anon, authenticated; +revoke all on function public.reject_style_revision_mutation() from public, anon, authenticated; + +grant execute on function public.save_style_preset_revision(uuid, text, uuid, text, integer, jsonb, text, text) to service_role; +grant execute on function public.save_episode_style_override(uuid, uuid, jsonb) to service_role; +grant execute on function public.save_scene_style_override(uuid, uuid, jsonb) to service_role; + +comment on table public.style_preset_revisions is + 'Owner-readable, immutable style preset revisions with allowlisted style configs.'; +comment on function public.save_style_preset_revision(uuid, text, uuid, text, integer, jsonb, text, text) is + 'Server-only style revision append with optimistic concurrency and owner-scoped series/season.'; diff --git a/supabase/migrations/20261120131000_v2_wo021_style_quota.sql b/supabase/migrations/20261120131000_v2_wo021_style_quota.sql new file mode 100644 index 00000000..91c39141 --- /dev/null +++ b/supabase/migrations/20261120131000_v2_wo021_style_quota.sql @@ -0,0 +1,27 @@ +-- V2 WO-021 follow-up: bounded style history. The preset row is updated +-- before the revision insert, so concurrent writers serialize per preset and +-- the quota cannot be exceeded by a race between two servers. +create or replace function public.enforce_style_revision_quota() +returns trigger language plpgsql set search_path = pg_catalog, public +as $$ +declare + v_count integer; +begin + select count(*) into v_count + from public.style_preset_revisions r + where r.owner_id = new.owner_id and r.preset_id = new.preset_id; + if v_count >= 200 then + raise exception 'style_revision_quota' using errcode = '23514'; + end if; + return new; +end; +$$; + +create trigger style_preset_revisions_quota + before insert on public.style_preset_revisions + for each row execute function public.enforce_style_revision_quota(); + +revoke all on function public.enforce_style_revision_quota() from public, anon, authenticated; + +comment on function public.enforce_style_revision_quota() is + 'Caps one preset at 200 revisions so the immutable history stays bounded.'; diff --git a/supabase/tests/rls_and_integrity.sql b/supabase/tests/rls_and_integrity.sql index ae3c2cda..98ab6270 100644 --- a/supabase/tests/rls_and_integrity.sql +++ b/supabase/tests/rls_and_integrity.sql @@ -2,7 +2,7 @@ -- The test uses synthetic JWT subjects and rolls back every inserted row. create extension if not exists pgtap with schema extensions; begin; -select plan(229); +select plan(242); do $$ declare @@ -18,7 +18,8 @@ declare 'character_identity_profiles', 'character_identity_profile_versions', 'visual_continuity_reports', 'cover_revisions', 'choice_end_cards', 'published_posts', 'published_post_versions', 'creative_variants', - 'retention_imports', 'analytics_snapshots', 'retention_experiments' + 'retention_imports', 'analytics_snapshots', 'retention_experiments', + 'style_presets', 'style_preset_revisions', 'episode_style_overrides', 'scene_style_overrides' ]; v_rls boolean; v_policy_count integer; @@ -68,7 +69,8 @@ begin 'character_identity_profiles', 'character_identity_profile_versions', 'visual_continuity_reports', 'cover_revisions', 'choice_end_cards', 'published_posts', 'published_post_versions', 'creative_variants', - 'retention_imports', 'analytics_snapshots', 'retention_experiments' + 'retention_imports', 'analytics_snapshots', 'retention_experiments', + 'style_presets', 'style_preset_revisions', 'episode_style_overrides', 'scene_style_overrides' ) then if v_policy_count <> 1 then raise exception 'edit plan policies must be read-only'; end if; if has_table_privilege('authenticated', format('public.%I', v_table), 'INSERT') @@ -2707,6 +2709,126 @@ select is( ); reset role; +set local role service_role; +select lives_ok( + $$select public.save_style_preset_revision( + '11111111-1111-4111-8111-111111111111', 'SERIES', + 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa', 'Série RLS', 0, + '{"schemaVersion":1,"captionTemplate":"horror"}'::jsonb, repeat('a', 64), 'DRAFT' + );$$, + 'service role stores the first style preset revision' +); +select throws_ok( + $$select public.save_style_preset_revision( + '11111111-1111-4111-8111-111111111111', 'SERIES', + 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa', 'Série RLS', 0, + '{"schemaVersion":1}'::jsonb, repeat('b', 64), 'DRAFT' + );$$, + '40001', 'style_revision_conflict', + 'style revisions require the current revision' +); +select lives_ok( + $$select public.save_style_preset_revision( + '11111111-1111-4111-8111-111111111111', 'SERIES', + 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa', 'Série RLS', 1, + '{"schemaVersion":1,"captionTemplate":"horror"}'::jsonb, repeat('a', 64), 'APPROVED' + );$$, + 'service role approves a new style preset revision' +); +select throws_ok( + $$update public.style_preset_revisions set status = 'DRAFT' where revision_number = 1;$$, + '55000', 'style_revision_is_immutable', + 'style preset revisions are immutable' +); +select lives_ok( + $$select public.save_episode_style_override( + '11111111-1111-4111-8111-111111111111', + 'b7b7b7b7-b7b7-47b7-87b7-b7b7b7b7b7b7', + '{"captionTemplate":"clean","reducedMotion":true}'::jsonb + );$$, + 'service role stores an episode style override' +); +select lives_ok( + $$select public.save_scene_style_override( + '11111111-1111-4111-8111-111111111111', + (select id from public.scenes + where episode_id = 'e6e6e6e6-e6e6-46e6-86e6-e6e6e6e6e6e6' and scene_index = 1), + '{"motion":"kinetic"}'::jsonb + );$$, + 'service role stores a scene style override' +); +select throws_ok( + $$select public.save_style_preset_revision( + '11111111-1111-4111-8111-111111111111', 'EPISODE', + 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa', 'Escopo inválido', 0, + '{}'::jsonb, repeat('c', 64), 'DRAFT' + );$$, + '23514', 'style_scope_invalid', + 'style presets accept only series or season scopes' +); +set local role authenticated; +select set_config('request.jwt.claims', '{"sub":"11111111-1111-4111-8111-111111111111","app_metadata":{"dif_studio_owner":true}}', true); +select is( + (select count(*) from public.style_preset_revisions), 2::bigint, + 'owner can read style revisions' +); +select throws_ok( + $$insert into public.style_presets (owner_id, scope_type, scope_id, name) + values ('11111111-1111-4111-8111-111111111111', 'SERIES', + 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa', 'Direto');$$, + '42501', 'permission denied for table style_presets', + 'owner cannot write style presets directly' +); +select set_config('request.jwt.claims', '{"sub":"22222222-2222-4222-8222-222222222222","app_metadata":{"dif_studio_owner":true}}', true); +select is( + (select count(*) from public.style_preset_revisions), 0::bigint, + 'second owner cannot read style revisions' +); +reset role; +select ok( + not has_function_privilege( + 'authenticated', + 'public.save_style_preset_revision(uuid,text,uuid,text,integer,jsonb,text,text)', + 'EXECUTE' + ) + and has_function_privilege( + 'service_role', + 'public.save_style_preset_revision(uuid,text,uuid,text,integer,jsonb,text,text)', + 'EXECUTE' + ), + 'style revision writes are service-role only' +); + +set local role service_role; +insert into public.style_preset_revisions ( + owner_id, preset_id, revision_number, config, config_hash, hash_version, status +) +select '11111111-1111-4111-8111-111111111111', + (select id from public.style_presets + where owner_id = '11111111-1111-4111-8111-111111111111' + and scope_id = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa'), + n, '{}'::jsonb, repeat('f', 64), 1, 'DRAFT' +from generate_series(3, 200) as n; +select is( + (select count(*) from public.style_preset_revisions + where owner_id = '11111111-1111-4111-8111-111111111111'), + 200::bigint, 'style history allows exactly 200 revisions per preset' +); +select throws_ok( + $$insert into public.style_preset_revisions ( + owner_id, preset_id, revision_number, config, config_hash, hash_version, status + ) values ( + '11111111-1111-4111-8111-111111111111', + (select id from public.style_presets + where owner_id = '11111111-1111-4111-8111-111111111111' + and scope_id = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa'), + 201, '{}'::jsonb, repeat('f', 64), 1, 'DRAFT' + );$$, + '23514', 'style_revision_quota', + 'style history blocks the 201st revision' +); +reset role; + select lives_ok( $$insert into public.hook_variants ( owner_id, episode_id, plan_id, plan_version, variant_key, label, objective, From bf3e9a95ff33a482364e1c18900dfc63ab2c2acf Mon Sep 17 00:00:00 2001 From: KayzenRoot <114633702+KayzenRoot@users.noreply.github.com> Date: Fri, 20 Nov 2026 10:39:44 -0300 Subject: [PATCH 2/9] =?UTF-8?q?fix(wo-021):=20preservar=20escopo=20em=20ov?= =?UTF-8?q?errides=20e=20validar=20importa=C3=A7=C3=A3o?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- e2e/style.spec.ts | 5 +++++ src/routes/app/style/+page.server.ts | 28 +++++++++++++++++++--------- 2 files changed, 24 insertions(+), 9 deletions(-) diff --git a/e2e/style.spec.ts b/e2e/style.spec.ts index 58b9ed73..9041f763 100644 --- a/e2e/style.spec.ts +++ b/e2e/style.spec.ts @@ -116,6 +116,11 @@ test('two series keep distinct style bibles, overrides stay local and import is await expect(betaPreview).toContainText('Comente B'); expect(await betaPreview.getAttribute('style')).toContain('--accent:#00ff00'); + // Opening the scope without an episode defaults the preview to that scope. + await openStyle(`/app/style?scopeType=SERIES&scopeId=${seriesB.seriesId}`); + await expect(page.locator('.effective-preview')).toContainText('Comente B'); + await expect(page.locator('.effective-preview')).toHaveClass(/font-serif/); + // Episode override wins over the series without editing the preset. await openStyle(seriesUrl(seriesA.seriesId, seriesA.episodeId)); const episodePanel = page diff --git a/src/routes/app/style/+page.server.ts b/src/routes/app/style/+page.server.ts index d986c02c..7089ed6b 100644 --- a/src/routes/app/style/+page.server.ts +++ b/src/routes/app/style/+page.server.ts @@ -110,9 +110,10 @@ function redirectFor(form: FormData, suffix: string): never { const scopeType = readFormText(form, 'scopeType') || 'SERIES'; const scopeId = readFormText(form, 'scopeId'); const episodeId = readFormText(form, 'episodeId'); + const sceneId = readFormText(form, 'sceneId'); redirect( 303, - `/app/style?scopeType=${scopeType}&scopeId=${scopeId}${episodeId ? `&episodeId=${episodeId}` : ''}&${suffix}`, + `/app/style?scopeType=${scopeType}&scopeId=${scopeId}${episodeId ? `&episodeId=${episodeId}` : ''}${sceneId ? `&sceneId=${sceneId}` : ''}&${suffix}`, ); } @@ -123,14 +124,24 @@ export const load: PageServerLoad = async (event) => { event.url.searchParams.get('scopeType') === 'SEASON' ? 'SEASON' : 'SERIES' ) as StyleScopeType; const requestedScopeId = event.url.searchParams.get('scopeId'); - const fallbackScopeId = - scopeType === 'SERIES' ? (context.series[0]?.id ?? '') : (context.seasons[0]?.id ?? ''); - const scopeId = requestedScopeId || fallbackScopeId; + const scopeOptions = scopeType === 'SERIES' ? context.series : context.seasons; + const fallbackScopeId = scopeOptions[0]?.id ?? ''; + const scopeId = scopeOptions.some((option) => option.id === requestedScopeId) + ? requestedScopeId! + : fallbackScopeId; const selectedPreset = context.presets.find( (preset) => preset.scopeType === scopeType && preset.scopeId === scopeId, ) ?? null; - const episodeId = event.url.searchParams.get('episodeId') || context.episodes[0]?.id || ''; + const scopeEpisodes = context.episodes.filter((episode) => + scopeType === 'SERIES' ? episode.seriesId === scopeId : episode.seasonId === scopeId, + ); + const requestedEpisodeId = event.url.searchParams.get('episodeId'); + const episodeId = + scopeEpisodes.find((episode) => episode.id === requestedEpisodeId)?.id ?? + scopeEpisodes[0]?.id ?? + context.episodes[0]?.id ?? + ''; let preview = null; let previewError: string | null = null; let scenes: Array<{ id: string; index: number }> = []; @@ -269,7 +280,7 @@ export const actions: Actions = { owner, payload: { ...source, - name: readFormText(form, 'targetName') || `${source.name} (cópia)`, + name: (readFormText(form, 'targetName') || `${source.name} (cópia)`).slice(0, 80), scopeType: readFormText(form, 'targetScopeType'), scopeId: readFormText(form, 'targetScopeId'), }, @@ -322,7 +333,7 @@ export const actions: Actions = { episodeId, config: overrideFromForm(form), }); - redirect(303, `/app/style?episodeId=${episodeId}&saved=override`); + redirectFor(form, 'saved=override'); } catch (cause) { rethrowRedirect(cause); const info = messageFor(cause); @@ -333,7 +344,6 @@ export const actions: Actions = { const { db, owner } = ownerDatabase(event); const form = await event.request.formData(); const sceneId = readFormText(form, 'sceneId'); - const episodeId = readFormText(form, 'episodeId'); if (!sceneId) return fail(400, { message: 'Cena inválida.' }); try { await saveSceneStyleOverride({ @@ -343,7 +353,7 @@ export const actions: Actions = { sceneId, config: overrideFromForm(form), }); - redirect(303, `/app/style?episodeId=${episodeId}&saved=scene-override`); + redirectFor(form, 'saved=scene-override'); } catch (cause) { rethrowRedirect(cause); const info = messageFor(cause); From d6a8b2d71a43ad70b1a65b04fdc98599e1ed6c54 Mon Sep 17 00:00:00 2001 From: KayzenRoot <114633702+KayzenRoot@users.noreply.github.com> Date: Fri, 20 Nov 2026 10:54:37 -0300 Subject: [PATCH 3/9] refactor(wo-021): reutilizar defaults e rejeitar SFX duplicado --- src/lib/domain/style-bible.test.ts | 8 +++ src/lib/schemas/style-bible.ts | 5 +- src/routes/app/style/+page.server.ts | 4 +- src/routes/app/style/StyleConfigFields.svelte | 55 +++++++------------ 4 files changed, 36 insertions(+), 36 deletions(-) diff --git a/src/lib/domain/style-bible.test.ts b/src/lib/domain/style-bible.test.ts index bfdf2734..cb8356b5 100644 --- a/src/lib/domain/style-bible.test.ts +++ b/src/lib/domain/style-bible.test.ts @@ -128,6 +128,14 @@ describe('style bible resolution', () => { }).success, ).toBe(false); expect(styleOverrideSchema.parse({})).toEqual({}); + expect( + styleOverrideSchema.safeParse({ + sfxAssetIds: [ + 'a1a1a1a1-a1a1-41a1-81a1-a1a1a1a1a1a1', + 'a1a1a1a1-a1a1-41a1-81a1-a1a1a1a1a1a1', + ], + }).success, + ).toBe(false); }); it('withdraws only missing or unlicensed SFX and keeps the rest', () => { diff --git a/src/lib/schemas/style-bible.ts b/src/lib/schemas/style-bible.ts index 79ed1afc..e8c4aeb3 100644 --- a/src/lib/schemas/style-bible.ts +++ b/src/lib/schemas/style-bible.ts @@ -40,7 +40,10 @@ const styleFields = { reducedMotion: z.boolean(), vhsIntensity: z.union([z.literal(0), z.literal(1), z.literal(2), z.literal(3)]), sfxCategory: z.enum(STYLE_SFX_CATEGORIES), - sfxAssetIds: z.array(uuid).max(8), + sfxAssetIds: z + .array(uuid) + .max(8) + .refine((ids) => new Set(ids).size === ids.length, 'SFX duplicado.'), voiceStyle: z.enum(STYLE_VOICE_STYLES), openingHookKind: z.enum(STYLE_OPENING_HOOKS), coverTemplateId: z.enum(COVER_TEMPLATE_IDS), diff --git a/src/routes/app/style/+page.server.ts b/src/routes/app/style/+page.server.ts index 7089ed6b..ca9c02c7 100644 --- a/src/routes/app/style/+page.server.ts +++ b/src/routes/app/style/+page.server.ts @@ -169,7 +169,9 @@ export const load: PageServerLoad = async (event) => { } } const notice = event.url.searchParams.get('saved') ? event.url.searchParams.get('saved') : null; - const selectedSceneId = event.url.searchParams.get('sceneId') || (scenes[0]?.id ?? ''); + const requestedSceneId = event.url.searchParams.get('sceneId'); + const selectedSceneId = + scenes.find((scene) => scene.id === requestedSceneId)?.id ?? scenes[0]?.id ?? ''; return { context, scopeType, diff --git a/src/routes/app/style/StyleConfigFields.svelte b/src/routes/app/style/StyleConfigFields.svelte index 2f37a921..fb61357b 100644 --- a/src/routes/app/style/StyleConfigFields.svelte +++ b/src/routes/app/style/StyleConfigFields.svelte @@ -1,6 +1,7 @@